我有模板代码需要将某些模板类型转换为字符串。为此,我为自己的类型重载了 to_string 。但类型也可以是字符串。然后编译失败,因为类型 string 本身没有重载 to_string (只是返回其参数)。
编辑:
示例代码:
template<class T>
class TemplatedClass
{
public:
string toString() const
{
// this should work for both simple types like int, double, ...
// and for my own classes which have a to_string overload
// and also for string, which is the reason for my question
return string("TemplatedClass: ").append(to_string(t_));
}
private:
T t_;
};
您可以使用适当的重载编写自己的模板化函数,如下所示:
#include <iostream>
#include <string>
using namespace std;
template<typename T>
std::string toString(const T& t) {
return std::to_string(t);
}
std::string toString(const char* t) {
return t;
}
std::string toString(const std::string& t) {
return t;
}
int main() {
cout << toString(10) << endl;
cout << toString(1.5) << endl;
cout << toString("char*") << endl;
cout << toString(std::string("string")) << endl;
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)