#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 发布