Type2Type

template <typename T> struct Type2Type
{
    typedef T OriginalType;
};
【用途】
比如说
template <class T,class U>
T* Create(const U& arg,T/*虚拟*/)
{
return new T(arg);
};
本模板函数用于使用U类型创建T类型。为了实例化时可以识别T,只能为函数增加一个T。但问题是,实例化的时候
string* pstr=Create("hello world!",string());
第2个参数需创建一个临时对象。但是这个临时对象却没有用,只是为了告诉该函数它的类型。当T这个类耗费很大时,这种方法是不好的。
【解决】
template <class T,class U>
T* Create(const U& arg,Type2Type<T>/*虚拟*/)
{
return new T(arg);
};
string* pstr=Create("hello world!",Type2Type<string>());
cout<<*pstr<<endl;
使用这种方法,就不会创建T对象了。

posted on 2012-08-07 17:55  山本二十八  阅读(311)  评论(0编辑  收藏  举报

导航