C++ プログラミングガイド

テンプレート定義内での修飾名の使用

C++ 標準は、テンプレート引数に依存する修飾名を持つ型を、typename キーワードを使用して型名として明示的に示すことを規定しています。これは、それが型であることをコンパイラが認識できる場合も同様です。次の例の各コメントは、それぞれの修飾名が typename キーワードを必要とするかどうかを示しています。


struct simple {
    typedef int a_type;
    static int a_datum;
};
int simple::a_datum = 0;      // 型ではない
template <class T> struct parametric {
    typedef T a_type;
    static T a_datum;
};
template <class T> T parametric<T>::a_datum = 0;       // 型ではない
template <class T> struct example {
    static typename T::a_type variable1;                       // 必要
    static typename parametric<T>::a_type variable2;       // 必要
    static simple::a_type variable3;                           // 不要
};			
template <class T> typename T::a_type                      // 必要
                   example<T>::variable1 = 0;              // 型ではない
template <class T> typename parametric<T>::a_type      // 必要
                   example<T>::variable2 = 0;              // 型ではない
template <class T> simple::a_type                          // 不要
                   example<T>::variable3 = 0;              // 型ではない
template class example<simple>

テンプレート宣言の入れ子

「>>」という文字を持つものは右シフト演算子と解釈されるため、あるテンプレート宣言を別のテンプレート宣言内で使用する場合は注意が必要です。隣接する「>」文字との間に、少なくとも 1 つの空白文字を入れるようにしてください。

以下に誤った書式の例を示します。


Array<String<10>> short_string_array(100); // >> は右シフトを示す。

上記の文は、次のように解釈されます。


Array<String<10  >> short_string_array(100);

正しい構文は次のとおりです。


Array<String<10> > short_string_array(100);