As stated here std::string
is not a template function but rather the standard choose to use function overloading to provide this function for different types. My question is why use overloading when template/specialisation seems to make more sense to me in this case? Consider that if the standard has defined something like this:
template <typename T>
std::string std::to_string(const T& v);
Then we can freely add specialisation for any type in our program to conform to this signature, thus C++ will have a uniform way to transform types into human-readable strings. Why not do this? What's the thinking behind the current design?
Edit 1:
The main critic I have for the current design is that adding an overload to std
is not allowed so we can not write anything like std:to_string(object-that-is-of-user-defined-types)
and has to fall back on defining a to_string()
in their own namespace and remember where to use their version or the std
version depends on the types they are dealing with... This sounds like a headache for me.
One thing I really liked about Python (or some other languages) is that you can make your own type work just like a native type by implementing some magic methods. I think what this question is fundamentally about is that why C++ decided to disallow people to implement std::to_string()
for their own type and thus forbid us from conforming to the same interface everywhere.
For common things like hash
or to_string()
, isn't it better to have a single interface on language/stdlib
level and then expect users to conform to that interface, rather than having multiple interfaces?