4

次のコードは正常に動作します。定義と用途を持つ単純なテンプレート クラスです。

#include <string>
#include <iostream>
using namespace std;

template<class T> class foo{
  public:
  string what();
};

template<class T> string foo<T>::what(){
  return "foo of type T";
}

int main(){
  foo<int> f;
  cout << f.what() << endl;
}

次に、次を追加すると(メインの上ですが、テンプレートクラス foo; の宣言の後)

template<> class foo<char>{
public:
  string what();
};
template<> string foo<char>::what(){
  return "foo of type char";
}

g++ からエラーが発生します

19 行目: エラー: 'std::string foo::what()' のテンプレート ID 'what<>' がどのテンプレート宣言とも一致しません

エラーを示すコードパッドは次のとおりです。http://codepad.org/4HVBn9oJ

私が犯している明らかな間違いは何ですか?または、これは c++ テンプレートでは不可能ですか? すべてのメソッドをインラインで定義すると (template<> foo の定義を使用して) 機能しますか?

ありがとうございました。

4

3 に答える 3

8
template<> class foo<char>{
public:
  string what();
};
/*template<>*/ string foo<char>::what(){
  return "foo of type char";
}

あなたはそれを必要としませんtemplate<>foo<char>特殊化された後、すでに完全なタイプです。

于 2011-04-18T12:29:31.737 に答える
2

これを次のように書きます。

#include <string>
#include <iostream>
using namespace std;

template<class T> class foo{
  public:
  string what();
};

template<class T> string foo<T>::what(){
  return "foo of type T";
}

template<> class foo<char>{
public:
  string what();
};

string foo<char>::what(){
  return "foo of type char";
}

int main(){
  foo<char> f;
  cout << f.what() << endl;
}

期待どおりに動作します。

于 2011-04-18T12:34:58.097 に答える
0

次に、次を追加すると(メインの上ですが、テンプレートクラス foo; の宣言の前に)

ジェネリック クラス テンプレートのに特殊化を定義します。

コンパイラが特殊化を確認するまでに、まず、これが特殊化されているクラス テンプレートを知る必要があります。したがって、論理的には、特殊化はジェネリック クラス テンプレートの後に表示する必要があります。

于 2011-04-18T12:28:40.167 に答える