繁体   English   中英

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

[英]What does “use of class template requires template argument list” mean?

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

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


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

    _getch();
}

编译错误:

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

使用

a<int> *a1(new a<int>(3));
 ^^^^^          ^^^^ 

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

template<class T>
a<T> * createA (const T& arg) //please add const to your ctor, too.
{
    return new a<T>(arg)
}
a(t& ii):i(ii){}

这应该是:

a(const t& ii):i(ii){}

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

然后这样做:

a<int> *a1(new a<int>(3));

你也可以写:

a<int> a2(3);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM