Convert int to string (As Well As Almost Anything)

This is a little code snippet from Open Yahtzee‘s code base that converts all the built-in types and many custom classes (ones that override the << operator) to string.

template <class T> inline std::string stringify(T x)
{
    std::ostringstream o;
    o << x;
    return o.str();
}

I first wrote it to convert ints to strings, but later I templatized it so it would work with other types as well. It’s a clean, elegant snippet that I thought others might find useful too.

Leave a Reply

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