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;
    }
  • 相关阅读:
    vi/vim 跳转到指定行
    svn如何过滤常见的bin/obj/package/log等文件夹的文件
    WIN10:你不能访问此共享文件夹,解决方法
    WinServer2019的IIS上无法安装framework3.5的问题
    浏览器播放实时视频,通过rtsp码流播放
    easyui comboxtree 如何获得选中值的其它属性
    iphone上传拍照图片时图片会旋转90度,从相册选择就不会,安卓手机也不会,怎么解决?
    如何快速清空微信浏览器中的缓存
    js种 new Date(str)的时候,在google下正常,ie11下异常的解决办法
    layer第二个按钮点击后关闭的解决方法
  • 原文地址:https://www.cnblogs.com/bayonetxxx/p/1603575.html
Copyright © 2011-2022 走看看