c++模板特化方法定义
c++ template specialisation method definition
下面的代码工作得很好,一个简单的模板类,具有定义和使用
#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声明之前)
在泛型类模板之后定义特化。
当编译器看到专门化时,它首先需要知道这是专门化的类模板。因此,从逻辑上讲,特化应该出现在泛型类模板之后的。相关文章:
- 在方法定义中显式指定命名空间
- 没有针对完全专用模板类的外联虚拟方法定义
- 将虚拟方法定义为私有方法时会发生什么情况?
- 单独的类声明和方法定义文件问题
- Eclipse CDT 不了解方法定义是什么
- C 方法定义具有模板
- Eclipse CDT将方法定义定义到标头文件
- 模板方法定义的问题 - 错误C2244:无法将函数定义与现有声明匹配
- 如何为 Product* getProductFromID(std::string)编写方法定义;.
- gdb 中的方法定义没有源代码
- 方法定义中的错误"passing const List<int> as this argument discards qualifiers"
- Sendmessage在方法定义内部无法正常工作
- C 公共方法定义后定义
- C++模板方法定义在类中不匹配
- 为什么通用模板方法定义与模板类专用化不匹配?
- 方法定义中的C++模板参数
- C++方法定义和变量声明
- 在继承层次结构中将方法定义为虚拟方法一次,以使多态性发挥作用
- 未为非访问器方法定义C++类属性
- 无法将一个类的方法定义为另一个类的好友