从参数中推导模板参数仅适用于函数,不适用于类。在你知道类的类型,即它的所有模板参数之前,你甚至不知道这个类有哪些成员函数!
所以,如果你想直接构造一个对象,你总是要说模板参数:
a<int> x(30);
这里有一个小思想实验来扩展上述内容。假设我们有
template <typename T> class Foo;
我们调用Foo::somefunction(x);,其中x 是某种类型。你想,好吧,我这样声明somefunction():
template <typename T> class Foo
{
static void somefunction(const T & x);
};
所以很明显T 与x 的类型相同。但现在想象一下我有一个专业:
template <> class Foo<char>
{
static void anotherfunction(double x);
};
Foo<char> 类甚至没有一个函数somefunction(),所以表达式Foo::somefunction(x) 甚至没有达到我可以查找参数的阶段! p>
解决这个问题的常用方法是创建一个免费的辅助函数来构造您的对象:
template <typename T> a<T> make_a(const T & x) { return a<T>(x); }
由于这是一个函数模板,它的参数可以推导出来:
make_a(30); // type a<int>
make_a("hello"); // type a<char[6]>