2017-11-22 5 views
0

私は以下のようにソースコードを書きました。 ----- sample.h ------g ++またはclang ++でテンプレートクラスをコンパイルできませんでした

#include <iostream> 
template <typename T> 
class Sample { 
private: 
static int foo; 
public: 
Sample (T number) { 
foo = number;} 
void display() { 
std :: cout << foo << std :: endl;} 
}; 

---- TEST.CPP --------------

#include "sample.h" 
template <> int Sample <float> :: foo; 


int main() { 
Sample <float> test (100.9); 
test.display(); 
return 0; 
} 

私はVisual Studio 2015コミュニティで正常にコンパイルされました。 しかし、g ++とclang ++(ubuntu linux 16.04 LTS)はリンク時に失敗しました。 g ++やclang ++でコンパイルしたいので、何かしたいのですが、 良いアイデアはありません。 g ++やclang ++の仕様と互換性がありませんか? コンパイラに精通している人はあなたですか?

答えて

1

GCCとクランは、ISO C++標準のドライ文字に従って正しい:

[temp.expl.spec]/13

テンプレートの静的データメンバーまたは静的の 明示専門の明示的な特化宣言にイニシャライザが含まれている場合、データメンバテンプレートは 定義です。それ以外の場合は、 が宣言です。 [注:デフォルト初期化が必要です テンプレートの静的データメンバーの定義は、 ブレース-INIT-リストを使用する必要があります。

template<> X Q<int>::x;       // declaration 
template<> X Q<int>::x();      // error: declares a function 
template<> X Q<int>::x { };      // definition 

- エンドノート]に適用

あなたの例は、定義ではなく別の宣言を提供することを意味します。そして、この修正は、初期化子を追加することです:

template <> int Sample <float> :: foo{}; // Default initialize `foo` 

それとも

template <> int Sample <float> :: foo{0.0}; // Direct initialize `foo` to 0 

それとも

template <> int Sample <float> :: foo = 0.0; // Copy initialize `foo` to 0 
関連する問題