C++如何调用模板化构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16242871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ how to call templated constructor
提问by duli
How can I change the code below to allow creation of a Base object with a templated constructor?
如何更改下面的代码以允许使用模板化构造函数创建 Base 对象?
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;
}
回答by Topological Sort
This thread seems to answer your question:
这个线程似乎回答了你的问题:
The bottom line is that it doesn't seem to be supported; and it's unclear what it would achieve.
最重要的是,它似乎不受支持;目前还不清楚它会实现什么。
回答by Scott Jones
The question is a bit vague. Is your intent to replace the "int a" in the Base ctor with "T a"? If so, you might want to use function template type inference, like this:
这个问题有点含糊。您是否打算将 Base ctor 中的“int a”替换为“T a”?如果是这样,您可能希望使用函数模板类型推断,如下所示:
template<typename T>
Base<T> CreateBase(T a)
{
return new Base<T>(a);
}
// Call site avoids template clutter
auto base = CreateBase(2);