Lingxi Li <
lilin...@gmail.com> writes:
> When some type T has overloaded `to_string()`, it is reasonable to
> also overload `operator<<()`, so you can do `cout << x` instead of
> `cout << to_string(x)`. It seems rather verbose and redundant to
> overload `operator<<()` for each such type. The standard library
> should do something so that once `to_string()` is overloaded, we can
> get `cout << x` support for free. Specifically, I propose to add the
> following two overloads to the standard library.
This question has been discussed on Stack Overflow before. (I assume
you are the author of that post.)
https://stackoverflow.com/questions/34940754/fallback-to-to-string-when-operator-fails
As I've mentioned in my answer there, `to_string` is just one of many
possible names. It is true that the standard library defines such
functions for integral types (but fore those, `operator<<` is already
overloaded anyway and ADL doesn't work for them) but then again, other
types from the standard library like string streams rather have a `str`
member function. `std::exception` has a `what` member function. Other
people might use even other spellings. If a type has both, an
ADL-findable `to_string` overload and a `str` member function, which one
do you want? Who is going to decide what names can reasonably be
expected to mean "this converts the type into a string representation"?
I believe that such a generic adapter can be useful for some code bases
where you can enable it explicitly. But the standard library should
stay away from adding a possibly confusing feature. I think that the
"official" guideline should remain: If you want your type to be
streamable, overload `operator<<` for it.
Finally, I think that it could often be easier to go the other way round
and implement `to_string` via `operator<<` (aka lexical cast).