c++stringc++11tostring

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


I just got to know that C++ has a std::to_string() defined in <string>. Now I wonder why to_string() only works with number types. Is there any particular reason, why there isnt a more general

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

?

Could be implemented like this:

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

I suspect that such general to_string does not exist, because it is easy to write your own, but the same argument would apply to the to_string() taking int,double, etc.


Solution

  • Because of the std::to_string() requirements.

    As the standard states:

    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.

    Writing a templated function that can determine the specifier that needs to be used for std::sprintf makes things unnecessarily complex.