メンバー・テンプレートと他の名前を区別するために、
キーワード template を修飾子として使用してください。
次の例は、template を修飾子として使用しなければならない状況を示しています。
class A { public: template<class T> T function_m() { }; }; template<class U> void function_n(U argument) { char object_x = argument.function_m<char>(); }
宣言 char object_x = argument.function_m<char>(); は、書式が不正です。 コンパイラーは、< が「より小演算子」であると見なします。 コンパイラーに関数テンプレート呼び出しを認識させるには、template 修飾子を追加する必要があります。
char object_x = argument.template function_m<char>();
メンバー・テンプレート特殊化の名前が、. 、->、 または :: 演算子の後で現れ、その名前が、 明示的に修飾されたテンプレート・パラメーターを持っている場合、 メンバー・テンプレート名の前にキーワード template を付けてください。 次の例は、このキーワード template の使用法を示しています。
#include <iostream> using namespace std; class X { public: template <int j> struct S { void h() { cout << "member template's member function: " << j << endl; } }; template <int i> void f() { cout << "Primary: " << i << endl; } }; template<> void X::f<20>() { cout << "Specialized, non-type argument = 20" << endl; } template<class T> void g(T* p) { p->template f<100>(); p->template f<20>(); typename T::template S<40> s; // use of scope operator on a member template s.h(); } int main() { X temp; g(&temp); }
次に、上記の例の出力を示します。
Primary: 100 Specialized, non-type argument = 20 member template's member function: 40
これらのケースでキーワード template を使用しない場合、 コンパイラーは、< を「より小演算子」として解釈します。 例えば、次のコード行は、書式が不正です。
p->f<100>();
コンパイラーは、f を非テンプレート・メンバーとして、 < を「より小演算子」として解釈します。
関連参照