为什么数字类型只有 `to_string()`?

Why there is only a `to_string()` for number types?

我刚刚知道 C++ 在 <string> 中定义了一个 std::to_string()。现在我想知道为什么 to_string() 只适用于数字类型。有什么特别的原因,为什么没有更通用的

template <typename T>
std::string to_string(const T& t);

?

可以这样实现:

template <typename T>
std::string to_string(const T& t) {
    std::ostringstream s;
    s << t;
    return s.str();
}

我怀疑这种笼统的to_string不存在,因为自己写起来很容易,但是同样的道理也适用于to_string()int,double,等等

因为 std::to_string() 要求。

如标准所述:

string to_string(int val);

string to_string(unsigned val);

string to_string(long val);

string to_string(unsigned long val);

string to_string(long long val);

string to_string(unsigned long long val);

string to_string(float val);

string to_string(double val);

string to_string(long double val);

Returns: Each function returns a string object holding the character representation of the value of its argument that would be generated by calling sprintf(buf, fmt, val) with a format specifier of "%d", "%u", "%ld", "%lu", "%lld", "%llu", "%f", "%f", or "%Lf", respectively, where buf designates an internal character buffer of sufficient size.

编写一个模板函数来确定需要用于 std::sprintf 的说明符会使事情变得不必要的复杂。

只想添加到 what I found in this proposal(感谢@DAle link)。

提案是关于添加通用 to_string 方法。原理与我天真的实现相同:在引擎盖下,流用于从任何可以流式传输的对象中获取字符串。

由于提案是在 c++11 之后提出的,添加这样的方法会对现有的 to_string 产生影响,他们在“对标准的影响”一节中写道:

[...] The old and new functions could coexist, relying on the overload resolution to prefer a non-templated (existing) version in case of a matching argument type. However, a compatibility problem may arise in case of some distinct but implicitly convertible argument types:

to_string(0);     // before: calls to_string(int), now: calls to_string(int)
to_string(false); // before: calls to_string(int), now: calls to_string<bool>(bool&&)
to_string('0');   // before: calls to_string(int), now: calls to_string<char>(char&&)

While the effect is identical in the first two cases (the result is always "0"), in the last one the result will change from "48" (assuming ASCII encoding) to "0". There are several ways to deal with problematic specialisation cases like this one:

然后他们列出了一些选项(包括忽略问题),其中 none 会非常令人满意。