我正在嘗試理解靜態資料成員模板的概念。我在一本書中遇到了以下示例:
class Collection {
public:
template<typename T>
static T zero = 0;
};
當我嘗試執行程式時,它給出的錯誤是:
undefined reference to `Collection::zero<int>'
為了解決上述錯誤,我嘗試在上面的程式中添加以下代碼,但它仍然給出錯誤:
template<typename T> T Collection::zero = 0; //even after adding this it still gives error
錯誤現在說:
duplicate initialization of 'Collection::zero'
我的問題是,這本書的這個例子是一個錯誤(錯字)。如果是,那么問題是什么,我該如何解決?
uj5u.com熱心網友回復:
是的,這是書中的一個錯字。問題是您已經為靜態資料成員模板指定了一個初始化程式,即使它不是inline。
解決方案
有兩種方法可以解決這個問題,這兩種方法都在下面給出。方法一:C 17
在 C 17 中,您可以使用關鍵字inline。
class Collection {
public:
template<typename T>
inline static T zero = 0; //note the keyword inline here
};
//no need for out of class definition of static data member template
int main(){
int x =Collection::zero<int>;
}
方法二:C 14
在這種情況下,您需要從靜態資料成員模板0的類內宣告中洗掉初始化程式。
class Collection {
public:
template<typename T>
static T zero ; //note initializer 0 removed from here since this is a declaration
};
template<typename T> T Collection::zero = 0;
int main(){
int x =Collection::zero<int>;
}
uj5u.com熱心網友回復:
這不是特定于模板的問題,而是類的靜態成員的初始化。不同之處在于,對于模板,您通常在標頭中有完整的實作,因此您沒有與此類相關的 cpp 檔案(也沒有編譯單元)。您可以添加此定義/初始化,例如在您的類中的 cpp 中或僅在您使用此模板的檔案中,這取決于您的專案的結構。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/421216.html
標籤:
