这可能是有人之前提出的问题,但我找不到它...
我在一个.hpp文件中有一个类:
我在一个.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}
但是当我使用带有 std::string
的函数 func
时,程序会调用数字的方法... 因此我将 .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}
然后一切都正常工作!
我的问题是,这是正确的做法吗?