#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
template<int v>
struct Int2Type
{
enum {value = v};
};
template <typename T, bool isPolymorphic>
class NiftyContainer
{
private:
T* pNewObj;
void DoSomething(T* pObj, Int2Type<true>)
{
pNewObj = pObj->Clone();
}
void DoSomething(T* pObj, Int2Type<false>)
{
pNewObj = new T(*pObj);
}
public:
void DoSomething(T* pObj)
{
DoSomething(pObj, Int2Type<isPolymorphic>());
cout<<*pNewObj<<endl;
delete pObj;
delete pNewObj;
}
};
class Test:public string
{
public:
Test(char* c):string(c){}
Test(string& str):string(str){}
Test* Clone(){return new Test(*this);}
};
int main(int argc, char *argv[])
{
NiftyContainer<int,false> ni1;
ni1.DoSomething(new int(4));
NiftyContainer<Test,true> ni2;
ni2.DoSomething(new Test("wch"));
system("PAUSE");
return EXIT_SUCCESS;
}
利用 Int2Type 进行函数类型切换
最新推荐文章于 2023-11-29 15:23:10 发布
本文介绍了一个使用C++模板元编程实现的智能容器类NiftyContainer,该容器能够根据不同类型的对象特性选择合适的复制方式:对于多态类型采用克隆的方式复制,而对于非多态类型则直接进行构造复制。
2044

被折叠的 条评论
为什么被折叠?



