zoukankan      html  css  js  c++  java
  • CPP Templates 之 模板继承的技巧

    // bolgcontent.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"
    #include <iostream>
    #include <string>

    using namespace std;

    /*类模板继承的例子
     *一、继承模板参数
     */

    template<typename Base,int D>
    class Discriminator:public Base{};

    /*二、递归模板模式
     *即派生类将本身作为模板参数传给基类,最简单情形如下
     */

    template <typename Derived>
    class CriousBase{
    //……
    };

    class Crious:public CriousBase<Crious>{};

    template<typename T>
    class CriousTemplate:public CriousBase<CriousTemplate<T> >
    {};

    //CRPT 的一个简单的应用就是记录每个类构造的总个数

    // templatetest.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"
    #include <iostream>
    #include <typeinfo>
    #include <string>

    using namespace std;

    template <typename CountedType>
    class ObjectCounter{
    private:
        static size_t count;
    protected:
        //缺省构造函数
        ObjectCounter(){
            ++ObjectCounter<CountedType>::count;
        }

        //拷贝构造函数
        ObjectCounter(ObjectCounter const &){
            ++ObjectCounter<CountedType>::count;
        }

        //析构函数
        ~ObjectCounter(){
            --ObjectCounter<CountedType>::count;
        };

    public:
        //返回存在对象的个数
        static size_t live(){
            return ObjectCounter<CountedType>::count;
        }
    };

    template<typename CountedType>
    size_t ObjectCounter<CountedType>::count=0;

    template <typename T>
    class countt:public ObjectCounter<countt<T>>
    {
    public:
        countt()
        {}

    };


    int _tmain(int argc, _TCHAR* argv[])
    {
        countt<int> tt;

        cout<<tt.live()<<endl;
        getchar();
        return 0;
    }



    //三、参数化虚拟性

    class NotVirtual{
    };

    class Virtual{
    public:
        virtual void foo(){
        }
    };

    template<typename VBase>
    class Base:private VBase{
    public:
        //foo()的虚拟性依赖于他的基类VBase中的声明
        void foo(){
            std::cout<<"Base::foo()"<<endl;
        }
    };

    template<typename V>
    class Derived:public Base<V>{
    public:
        void foo(){
            std::cout<<"Derived::foo()"<<endl;
        }
    };

    int _tmain(int argc, _TCHAR* argv[])
    {
        Base<NotVirtual> *p1=new Derived<NotVirtual>;
        p1->foo();//调用Base::foo()

        Base<Virtual> *p2=new Derived<Virtual>;
        p2->foo();//调用Derived::foo()

        return 0;
    }
  • 相关阅读:
    【POJ】【2104】区间第K大
    【BZOJ】【2595】【WC2008】游览计划
    【BZOJ】【1036】树的统计
    【BZOJ】【2038】小Z的袜子
    我的博客~
    CSS选择器
    CSS样式表分类
    python奇闻杂技03 三元表达式示例,函数定义示例,七段彩码管绘制示例
    python奇闻杂技02 time模块,文本进度条示例,数字类型操作,字符串操作
    python奇闻杂技01 turtle学习
  • 原文地址:https://www.cnblogs.com/bayonetxxx/p/1603575.html
Copyright © 2011-2022 走看看