Saturday 16 April 2011

Create string on the fly just in one line

We often make use of std::stringstream to convert values of various types into a single std::string. For example, see this:

std::stringstream ss;
ss << 25 << " is greater than " << 5;
std::string s = ss.str(); //s => "25 is greater than 5"

Paul (at stackoverflow) was trying to think of a clever way to concatenate various things into a single string without having to use an ostringstream explicitly. He came up with a macro which he didn't like though.
That made me think that it would be really good if we've something that can do such thing very elegantly, without having to write many lines of code involving std::stringstream. So I came up with this stringbuilder class.

struct stringbuilder
{
   std::stringstream ss;
   template<typename T>
   stringbuilder & operator << (const T &data)
   {
        ss << data;
        return *this;
   }
   operator std::string() { return ss.str(); }
};

With this class, we can create strings out of values of various types in just one line, and this class can be used in many different ways. Few examples,

void f(const std::string & s ) 
{
  std::cout << s << std::endl;
}
 
std::string g(int m, int n) 
{
    //create string on the fly and returns it
    if ( m < n )
        return stringbuilder() << m << " is less than " << n ;
    return stringbuilder() << n << " is less than " << m ;
}
 
int main() 
{
  char const *const pc = "hello";
 
  //create string on the fly and pass to the function
  f(stringbuilder() << '{' << pc << '}' );
 
  std::cout << g(10, 30) << std::endl;
 
  //this is my most favorite line
  std::string s = stringbuilder() << 25  << " is greater than " << 5 ;
  std::cout << s << std::endl;
 
}

Complete demo at ideone.


No comments:

Post a Comment