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 string, but later I templatized it so it would work with other types as well. It’s a clean elegant snippet that I thought other might find useful too.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.