2015-12-29 27 views
5

それはextern template declarationexplicit template instantiationに来るときtypedefは私を混乱させる2つのケースがあります。テンプレートのインスタンスとのexternテンプレート宣言にtypedefを使用して

2つの例を示すには、次の2つのコードスニペットを参照してください。

は例(ケース1)次の点を考慮

// suppose following code in some cpp file  
template <typename T> 
    struct example 
{ 
    T value; 
}; 

// valid typedefs 
typedef example<int> int_example; 
typedef example<std::string> string_example; 

// explicit instantiation using above typedefs 
template class int_example; // -> compile time error 
template class string_example; // -> compile time error 

// instead we need to use type names 
template class example<int>; // -> OK 
template class example<std::string>; // -> OK 

// QUESTION 1: Why does this work however? is this valid code? 
typedef std::string type_string; 
template class example<type_string>; 

なぜtypedefを持つtemplate class example<type_string>仕事?なぜtemplate class string_exampleは有効ではありませんか?

次の例(ケース2)考えてみましょう:上記のコメントに疑問として、それは上記の例のように、extern template declarationにtypedefを使用して有効であり、そしてなぜこれがとは違ってコンパイルん

// suppose following code is in some header file 
template <typename T> 
struct example 
{ 
    T value; 
}; 

// valid typedefs 
typedef std::string type_string; 
typedef example<type_string> string_example; 

// Explicit instantiation declaration 
// QUESTION 2: Is this valid code? if not why not? 
extern template string_example; // -> at least this compiles, but is it OK? 

ケース1ここではありません。

私は同様のケースについて読んだことがありますが、上記の2つの質問に対する詳細な答えはありません。詳細な精緻化が非常に高く評価されています!

答えて

2
template class int_example; 

は法的ではありません。 C++ 11 Stanardから:

14.7.2明示的なインスタンス

2明示的なインスタンス化のための構文は次のとおりです。

明示的インスタンス化:templateオプト
extern宣言

明示的なインスタンス化には、明示的なインスタンス化の定義と明示的なインスタンス化の宣言の2つの形式があります。明示的なインスタンス化の宣言は、externキーワードで始まります。明示的なインスタンスは、クラスまたはメンバークラスである場合

3は、は詳述型指定子宣言シンプル・テンプレートIDを含まなければなりません。

シンプル・テンプレートIDセクションA.で定義され

シンプルなテンプレート-ID:など12個のテンプレート
テンプレート名<テンプレート引数リストオプト>

int_exampleはとしての資格はありません簡易テンプレートID
​​は、simple-template-idとなります。

しかし、そのロジックにより、

extern template string_example; 

がいずれかの法的ではありません。私はそれがあなたのためにどのように機能するのか分かりません。このような行をg ++ 4.9.3でコンパイルしようとすると、次のエラーが出ます。

socc.cc:15:31: error: expected unqualified-id before ‘;’ token 
extern template string_example; // -> compile time error 
+0

あなたはなぜ 'テンプレートクラスの例を知っていますか;'と 'のexternテンプレートクラスの例;'は動作します(またはそれがGCCでない)、私はところでMSVC-140を使用していますし、それが動作します。本当にありがとう! – codekiddy

+0

'example 'は* simple-template-id *とみなされます。 –

+0

GCCでいくつかのテストを行いましたが、g ++が 'example 'のような場合に未定義の参照を発行するケースがありますが、msvcはうまくコンパイルされますが、msvcが警告を出すがg ++ではない場合もあります。どちらもスタンダードによって記載されておらず、よく定義さ – codekiddy

関連する問題