【转】traits技术及模板偏特化

时间:2022-04-27 16:29:35
#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 = ;
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