C++模板特化方法定义

标签 c++ templates specialization

下面的代码工作正常,一个简单的模板类,有定义和使用

#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++ 得到一个错误

Line 19: error: template-id 'what<>' for 'std::string foo::what()' does not match any template declaration

这是一个显示错误的键盘: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>特化后已经是一个完整的类型。

关于C++模板特化方法定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5702849/

相关文章:

c++ - C++ 模板/通用/元编程的最佳设置

c++ - 模板转换运算符问题

c++ - C++ 中的模板特化

c++ - 特定成员的模板特化?

C++ 外部枚举

c++ - 覆盖文件而不会有损坏文件的风险

c++ - 将函数传递给方法原型(prototype)

c++ - 将成员函数作为参数传递给其他成员函数 (C++ 11 <function>)

c++ - 编译时输出一个模板类名

c++ - 使用默认参数专门化内部模板