次のコードは正常にビルドできます。
#include <iostream>
#include <string>
using namespace std;
template <class T>
struct Foo
{
template <class S>
void print(const T& t, const S& s);
};
template <>
struct Foo<int>
{
template <class S>
void print(const int& t, const S& s)
{
cout << s << " " << t << endl;
}
};
int main(void)
{
string str("hello");
Foo<int> foo;
foo.print(7, str);
return 0;
}
しかし、メンバー関数Foo<int>::print(...)
の定義をFoo<int>
以下のようにクラスの定義の外に移動すると、
template <>
template <class S>
void Foo<int>::print(const int& t, const S& s)
{
cout << s << " " << t << endl;
}
次のようなGCCコンパイルエラーが発生しました。
error: too many template-parameter-lists
void Foo<int>::print(const int& t, const S& s)
^
どこで間違えたの?
§14.7.3[temp.expl.spec] / p5:
明示的に特殊化されたクラステンプレートのメンバーは、通常のクラスのメンバーと同じ方法で定義され、
template<>
構文は使用されません。明示的に特殊化されたメンバークラスのメンバーを定義する場合も同様です。ただし、template<>
クラステンプレートとして特殊化された明示的に特殊化されたメンバークラステンプレートのメンバーを定義する際に使用されます。
print
クラステンプレートではありません。したがって、template <>
:を削除します
template <>
struct Foo<int>
{
template <class S>
void print(const int& t, const S& s);
};
template <class S>
void Foo<int>::print(const int& t, const S& s)
{
cout << s << " " << t << endl;
}
デモ。
を明示的に特殊化せずに直接Foo<int>
定義しようとするFoo<int>::print
と、の特定の暗黙的なインスタンス化のメンバーを明示的に特殊化し、明示的な特殊化のメンバーを定義しないことに注意してくださいFoo
。そのためには、次のものが必要ですtemplate <>
。
template <class T>
struct Foo
{
template <class S>
void print(const T& t, const S& s);
};
template <>
template <class S>
void Foo<int>::print(const int& t, const S& s)
{
cout << s << " " << t << endl;
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加