什么是“最好”的方法是一个悬而未决的问题。
有几种方法。
首先要说的是超载std::to_string
对于自定义类型是不允许。我们可能只专门化模板函数和类 in the std
自定义类型的命名空间,以及std::to_string
不是模板函数。
据说有一个好的治疗方法to_string
很像一个运算符或一个实现swap
。即允许参数依赖查找来完成工作。
因此,当我们想将某些内容转换为字符串时,我们可以这样写:
using std::to_string;
auto s = to_string(x) + " : " + to_string(i);
假设 x 是命名空间 Y 中类型 X 的对象,而 i 是 int,那么我们可以定义:
namespace Y {
std::string to_string(const X& x);
}
现在这意味着:
调用to_string(x)
实际上选择Y::to_string(const Y::X&)
, and
调用to_string(i)
选择std::to_string(int)
更进一步,您可能希望 to_string 执行与运算符
namespace Y {
inline std::ostream& operator<<(std::ostream& os, const X& x) { /* implement here */; return os; }
inline std::string to_string(const X& x) {
std::ostringstream ss;
ss << x;
return ss.str();
}
}