c++模板特化方法定义

c++ template specialisation method definition

本文关键字:方法 定义 c++      更新时间:2023-10-16

下面的代码工作得很好,一个简单的模板类,具有定义和使用

#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;
}

如果我然后添加以下代码(在main之上,但在模板类foo的声明之后)

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

从g++

得到一个错误

第19行:error: template-id 'what<>对于'std::string foo::what()'不匹配任何模板声明

下面是显示错误的代码:http://codepad.org/4HVBn9oJ

我犯了什么明显的错误?或者这是不可能与c++模板?将所有的方法定义内联(与template<> foo的定义)工作吗?

再次感谢大家

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

你不需要那个template<>foo<char>专门化后已经是一个完整的类型

这样写:

#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;
}

按预期工作。

如果我随后添加以下代码(在main之上,但在模板类foo声明之前)

在泛型类模板之后定义特化

当编译器看到专门化时,它首先需要知道这是专门化的类模板。因此,从逻辑上讲,特化应该出现在泛型类模板之后的