这可能是一个有人问过的问题,但我找不到...
我在.hpp
文件中有一个课:
class A{
public:
A(){//constructor}
~A(){//destructor}
//some public methods and arguments
template<typename Type>
void func(Type t){//do something for numbers}
private:
//some private methods and arguments
}
模板方法应该适用于int,double ...,但不适用于字符串。因此,在.hpp
文件中,我定义了func
数字的含义,并在.cpp
文件中写道:
template<>
void A::func(std::string t){ // do something in that case}
但是当我将函数func
与一起使用时std::string
,程序会调用数字的方法...因此我将.hpp
文件替换为:
class A{
public:
A(){//constructor}
~A(){//destructor}
//some public methods and arguments
template<typename Type>
void func(Type t){//do something for numbers}
void func(std::string s);
private:
//some private methods and arguments
}
和我的.cpp
文件成为:
void A::func(std::string t){ // do something in that case}
然后一切正常!
我的问题是,这是正确的方法吗?
这不是部分专门化(没有模板参数未进行专门化),而是显式专门化。
模板必须是可见的代码使用它们,如果你不声明在头文件中的专业化然后代码试图调用A::func
一个string
将实例主模板(一个为数字)和使用,因为他们不”甚至不知道字符串专业化存在。
因此,您必须(至少)在标头中声明特殊化,以使其在.cpp
文件中超越使用:
template<>
void A::func(std::string t);
但是,使用过载的替代方法更简单,并且完全可以接受。之所以起作用,string
是因为在标头中声明了for的重载,因此调用它的代码知道要调用哪个函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句