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

  • 相关阅读:
    Windows下建立FTP服务器站点
    Markdown语法指南
    Win7系统修改hosts无法保存怎么办?
    PHP 7 错误处理 Error
    strtotime 的 BUG
    三角箭头 css实现
    关于 layer.open 动态赋值不了的问题
    layui layer.open弹出框获取不了 input框的值
    webhook 自动部署代码
    lnmp 命令 及其 TP5 部署遇到的一些问题
  • 原文地址:https://www.cnblogs.com/budapeng/p/5237629.html
Copyright © 2011-2022 走看看