簡體   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