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
Better way would be to create your own function that make use of std::to_string if it's possible as well as the .toString() method whenever it's available for passed argument:
#include
#include
#include
struct MyClass {
std::string toString() const { return "MyClass"; }
};
template
typename std::enable_if().toString()), std::string>::value, std::string>::type my_to_string(const T &t) {
return t.toString();
}
template
typename std::enable_if())), std::string>::value, std::string>::type my_to_string(const T &t) {
return std::to_string(t);
}
int main() {
std::cout << my_to_string(MyClass()) << std::endl; // will invoke .toString
std::cout << my_to_string(1) << std::endl; //will invoke std::to_string
}