#includeusing namespace std;struct __xtrue_type { }; // define two mark-typestruct __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 Traitstemplate 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 ComplexObjecttemplate <>struct Traits { typedef __xtrue_type has_clone_method;};template class XContainer{ template 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 ::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 n1; XContainer n2; XContainer n3; n1.clone(p1); n2.clone(p2); n3.clone(p3);}
摘自:http://www.cppblog.com/woaidongmao/archive/2008/11/09/66387.html