C++ – How to convert anything to string?

Well, at least anything that can be printed. It’s quite easy.

  1. Create a string stream
  2. “Print” the value to the stream
  3. Get a string from the string stream

I like to wrap it in a template function like that:

#include <string>
#include <sstream>

template <typename T>
string to_string(T x)
{
    stringstream ss;
    ss<<x;
    return ss.str();
}

You can make the function inline, and get the argument as a reference to const if you want.

Have you got a simpler generic solution?

Leave a Reply

Your email address will not be published. Required fields are marked *