In C++11 and later, is it allowed to specialize std::to_string in the std namespace for custom types?
namespace std {
string to_str
In C++11 and later, is it allowed to specialize std::to_string in the std namespace for custom types?
No, you can't add an overload into the std namespace for to_string().
The good news is that you don't need to, there is a simple solution!
You can provide your own implementation and let ADL (argument dependent lookup) solve the problem for you.
Here's how:
class A {};
std::string to_string(const A&)
{
return "A()";
}
int main()
{
A a;
using std::to_string;
std::cout << to_string(2) << ' ' << to_string(a);
}
Here we used the using declaration to bring std::to_string into the scope, and then we used the unqualified call to to_string().
Now both std::to_string and ::to_string are visible and the compiler picks the appropriate overload.
If you don't want to write using std::to_string before using to_string every time or you fear you will forget to use to_string without the namespace you can create an helper function
template
std::string my_to_string(T&& t)
{
using std::to_string;
return to_string(std::forward(t));
}
Note that this function can be defined in any namespace and works independently of the namespace in which the classes are defined (they don't have to be the same).
See the example.
NOTE: this works if you are the one calling to_string. If there is a library that calls std::to_string and you want to change it for your types you are out of luck.