- 论坛徽章:
- 0
|
- #include<iostream>
- using std::cout;
- using std::endl;
- struct __xtrue_type { }; // define two mark-type
- struct __xfalse_type { };
- class CComplexObject{
- public:
- virtual void clone() { cout << "in clone" << endl; }
- };
- class CDerivedComplexObject : public CComplexObject {
- public:
- virtual void clone() { cout << "in derived clone" << endl; }
- };
- template <typename T>
- struct Traits{ typedef __xfalse_type has_clone_method;};
- template <>
- struct Traits<CComplexObject>{ typedef __xtrue_type has_clone_method;};
- template <typename T>
- class XContainer{
- public:
- template <typename flag, typename N=void>
- class Impl { };
- template <typename N>
- class Impl <__xtrue_type,N>
- {
- public:
- void clone(T* pObj) { pObj->clone(); }
- };
- template <typename N>
- class Impl <__xfalse_type,N>
- {
- public:
- void clone(T* pObj) { }
- };
- public:
- void clone(T* pObj){ Impl< typename Traits<T>::has_clone_method >().clone(pObj); }
- };
- int main()
- {
- XContainer<CComplexObject> a;
- CComplexObject k;
- CDerivedComplexObject j;
- a.clone(&k);
- a.clone(&j);
- return 0;
- }
复制代码 补上一个简单的main后,编译成功,运行结果如下:- ???@atom:~$ ./a.out
- in clone
- in derived clone
复制代码 |
|