I know it seems too much Java or C#. However, is it possible/good/wise to make my own class valid as an input for the function std::to_string
?
Example:
<
First, some ADL helping:
namespace notstd {
namespace adl_helper {
using std::to_string;
template
std::string as_string( T&& t ) {
return to_string( std::forward(t) );
}
}
template
std::string to_string( T&& t ) {
return adl_helper::as_string(std::forward(t));
}
}
notstd::to_string(blah)
will do an ADL-lookup of to_string(blah)
with std::to_string
in scope.
We then modify your class:
class my_class{
public:
friend std::string to_string(my_class const& self) {
return "I am " + notstd::to_string(self.i);
}
int i;
};
and now notstd::to_string(my_object)
finds the proper to_string
, as does notstd::to_string(7)
.
With a touch more work, we can even support .tostring()
methods on types to be auto-detected and used.