"使用类模板需要模板参数列表"是什么意思?

raj*_*han 7 c++ templates

我是模板的新手所以请原谅我天真的问题.我在这段代码中遇到错误:

template <class t>
class a{
public:
    int i;
    a(t& ii):i(ii){}
};


int main()
{
    a *a1(new a(3));
    cout<<a1.i;

    _getch();
}
Run Code Online (Sandbox Code Playgroud)

编译错误:

  1. 'a' : use of class template requires template argument list
  2. 'a' : class has no constructors

Arm*_*yan 10

使用

a<int> *a1(new a<int>(3));
 ^^^^^          ^^^^ 
Run Code Online (Sandbox Code Playgroud)

如果希望自动推导出模板参数,可以使用辅助函数:

template<class T>
a<T> * createA (const T& arg) //please add const to your ctor, too.
{
    return new a<T>(arg)
}
Run Code Online (Sandbox Code Playgroud)


Naw*_*waz 6

a(t& ii):i(ii){}
Run Code Online (Sandbox Code Playgroud)

这应该是:

a(const t& ii):i(ii){}
Run Code Online (Sandbox Code Playgroud)

这样你就可以将const文字和临时文本传递给构造函数.

然后这样做:

a<int> *a1(new a<int>(3));
Run Code Online (Sandbox Code Playgroud)

你也可以写:

a<int> a2(3);
Run Code Online (Sandbox Code Playgroud)