[英]How to force compiler to deduce a class template argument?
我是C ++模板的新手,但我(很多失敗)試圖強制編譯器在初始化時推斷出模板typename參數。
這是我的代碼。
template <typename T>
class C
{
public:
T a;
C(T a) : a(a) {}
C(const C<T>& other) : a(other.a) {}
};
int main()
{
C<int> x(1);
C y{ x };
return 0;
}
由g ++編譯的該代碼將導致錯誤。
test.cpp:13:11: error: missing template arguments before ‘y’
C y{ x };
^
我想保持這種語法-只是C,而沒有明確指定template參數。
我曾嘗試使用演繹指南,但這僅引發了另一個錯誤。
template <typename T> C(const C<T>& other) -> C<T>;
當我將此行插入C類的定義下方時,我得到了。
test.cpp:10:51: error: expected constructor, destructor, or type conversion before ‘;’ token
template <typename T> C(const C<T>& other) -> C<T>;
^
當我將此行放入C類定義(在頂部)時,發生了另一個錯誤。
C(const C<T>& other) -> C<T>;
test.cpp:4:26: error: ‘C’ function with trailing return type not declared with ‘auto’ type specifier
C(const C<T>& other) -> C<T>;
^~~~
在這兩種情況下,仍然存在首次提及錯誤。
謝謝!
在C ++ 11中,僅模板函數可以推導其模板參數。 例如,給定:
void f(std::pair<int, char> &s);
,有人可以這樣稱呼它
f(std::make_pair(5, 'c'));
,因為std::make_pair
是一個函數,可以為函數推導模板參數。
但是,用一對來稱呼是非法的:
f(std::pair(5, 'c'));
,因為類模板沒有模板參數推導。 此問題已在C ++ 17中修復,使std::make_pair
有點過時了。
有關新類模板參數推導的更多信息,請參見此處 。
為了解決您的問題,在使用C ++ 11使用gcc進行編譯時,我已經遇到了相同的錯誤。 代碼使用C ++ 17編譯時沒有錯誤(對於gcc,可以通過傳遞-std=c++17
參數來完成)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.