Convert any type to strings with streams

Include this if you want to use a templated function that converts any possible type to a string, automagically. As long as the templated class has defined a << streaming operator. Here you can find it the way I like my code styled, intended, etc. It returns a string, can't be better, a string can easily be inserted in most C++ code.

#include <string>

#include <sstream>

template <class T> std::string toString( const T & t) {

  std::ostringstream oss; // create a stream
  oss << t; // insert value to stream
  return oss.str(); // extract value and return
}

Sure, if we want a char*, then we just copy/paste the following:

#include <string>

#include <sstream>

template <class T> char* toCharPointer( const T & t) {

  std::ostringstream oss; // create a stream
  oss << t; // insert value to stream
  return oss.str().c_str(); // extract value and return
}

comments powered by Disqus