2013-04-26 68 views
3

如何更改下面的代码以允许使用模板构造函数创建基本对象 ?C++如何调用模板化构造函数

struct Base { 
template <typename T> 
Base(int a) {} 
}; 

int main(int argc, char const *argv[]) 
{ 
    Base *b = new Base<char>(2); 
    delete b; 
    return 0; 
} 

回答

-1

此线程似乎回答你的问题:

C++ template constructor

的底线是,它似乎并没有得到支持;目前还不清楚它会实现什么。

+0

有时构造处理多种类型,但该数据仅用于暂时,所以其本身作为模板类是reduntant。我猜想没有什么大的需求,但它是有道理的。 – iPherian 2016-11-03 22:42:21

0

这个问题有点含糊。您是否打算用“T a”替换Base ctor中的“int a”?如果是这样,你可能想使用函数模板类型推断,像这样:

template<typename T> 
Base<T> CreateBase(T a) 
{ 
    return new Base<T>(a); 
} 

// Call site avoids template clutter 
auto base = CreateBase(2); 
相关问题