zoukankan      html  css  js  c++  java
  • 【转】traits技术及模板偏特化

    #include <iostream>
    using namespace std;
    
    struct __xtrue_type { }; // define two mark-type
    struct __xfalse_type { };
    
    class CComplexObject // a demo class
    {
    public:
         virtual void clone() { cout << "in clone" << endl; }
    };
    
    class CDerivedComplexObject : public CComplexObject // a demo derived class
    {
    public:
         virtual void clone() { cout << "in derived clone" << endl; }
    };
    
    // A general edtion of Traits
    template <typename T>
    struct Traits
    {
         typedef __xfalse_type has_clone_method; // trait 1: has clone method or not? All types defaultly has no clone method.
    };
    
    // Specialized edtion for ComplexObject
    template <>
    struct Traits<CComplexObject>
    {
         typedef __xtrue_type has_clone_method;
    };
    
    template <typename T>
    class XContainer
    {
         template <typename flag>
             class Impl
         {
         };
         template <>
             class Impl <__xtrue_type>
         {
         public:
             void clone(T* pObj)
             {
                 pObj->clone();
             }
         };
         template <>
             class Impl <__xfalse_type>
         {
         public:
             void clone(T* pObj)
             {
             }
         };
    public:
         void clone(T* pObj)
         {
             Impl<Traits<T>::has_clone_method>().clone(pObj);
         }
    };
    
    void main()
    {
         int* p1 = 0;
         CComplexObject c2;
         CComplexObject* p2 = &c2;
         CDerivedComplexObject c3;
         CComplexObject* p3 = &c3; // you must point to a derived object by a base-class pointer,
                                 //it's a little problem
    
         XContainer<int> n1;
         XContainer<CComplexObject> n2;
         XContainer<CComplexObject> n3;
    
         n1.clone(p1);
         n2.clone(p2);
         n3.clone(p3);
    }

    摘自:http://www.cppblog.com/woaidongmao/archive/2008/11/09/66387.html

  • 相关阅读:
    python定义函数的三种形式
    python函数的返回值
    python函数的调用
    python函数的定义
    python文件操作
    Python2和3字符编码的区别
    python的字符编码
    python异常处理
    python深浅拷贝
    python色彩缤纷的python(改变字体颜色以及样式)
  • 原文地址:https://www.cnblogs.com/budapeng/p/5237629.html
Copyright © 2011-2022 走看看