#include <iostream>usingnamespacestd;classCComplexObject// a demo class{public:voidclone(){cout<<"in clone"<<endl;}};// Solving the problem of choosing method to call by inner traits classtemplate<typenameT,boolisClonable>classXContainer{public:enum{Clonable=isClonable};voidclone(T*pObj){Traits<isClonable>().clone(pObj);}template<boolflag>classTraits{};template<>classTraits<true>{public:voidclone(T*pObj){cout<<"before cloning Clonable type"<<endl;pObj->clone();cout<<"after cloning Clonable type"<<endl;}};template<>classTraits<false>{public:voidclone(T*pObj){cout<<"cloning non Clonable type"<<endl;}};};voidmain(){int*p1=0;CComplexObject*p2=0;XContainer<int,false>n1;XContainer<CComplexObject,true>n2;n1.clone(p1);n2.clone(p2);}
输出:
doing something non Clonable
before doing something Clonable
in clone
after doing something Clonable
#ifndef MY_DESTRUCT_H#define MY_DESTRUCT_H#include <iostream>#include "my_type_traits.h"usingstd::cout;usingstd::endl;template<classT1,classT2>inlinevoidmyconstruct(T1*p,constT2&value){new(p)T1(value);}template<classT>inlinevoidmydestroy(T*p){typedeftypenamemy_type_traits<T>::has_trivial_destructortrivial_destructor;_mydestroy(p,trivial_destructor());}template<classT>inlinevoid_mydestroy(T*p,my_true_type){cout<<" do the trivial destructor "<<endl;}template<classT>inlinevoid_mydestroy(T*p,my_false_type){cout<<" do the real destructor "<<endl;p->~T();}#endif