下面的代码工作正常,一个简单的模板类,有定义和使用
#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/