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:
<
This already has a great answer but I'd like to propose an alternative, feedback is welcome.
If you're not dead set on the to_string function name, you could implement your own ToString free function template, with specializations for the types supported by to_string:
template
std::string ToString(const T& t)
{
std::ostringstream stream;
const uint8_t* pointer = &t;
for(size_t i=0;i std::string ToString(const int& t) { return std::to_string(t); }
template<> std::string ToString(const long& t) { return std::to_string(t); }
template<> std::string ToString(const long long& t) { return std::to_string(t); }
template<> std::string ToString(const unsigned& t) { return std::to_string(t); }
template<> std::string ToString(const unsigned long& t) { return std::to_string(t); }
template<> std::string ToString(const unsigned long long& t) { return std::to_string(t); }
template<> std::string ToString(const float& t) { return std::to_string(t); }
template<> std::string ToString(const double& t) { return std::to_string(t); }
The default implementation here returns a string of hex values with the values at the memory space for the class reference passed, while the specializations call std::to_string, this will make any class "stringable".
Then you just need to implement your own specialization for your class:
template<> std::string ToString(const my_class& t) { return "I am " + std::to_string(t.i); }