Posted by: sureshamrita | August 24, 2011

Concatenating arbitrary number/types of arguments into a string

When exceptions are thrown from code, to make the received message meaningful, many a time one would like to combine variable values and strings into a const string. For example, if an exception is thrown because an argument is negative, one would like the message thrown to look like,  “expecting positive arguments, but the current value of the argument is  10″.   In order to create such strings, we need a function which can accept arbitrary number of arguments of arbitrary types and then concatenate all of them into a string. The following code does just that.

#include <sstream>
#include <iostream>
#include <string>

using namespace std;

class Mystrcat{
public:
  template<typename T, typename ...P>
  explicit Mystrcat(T t, P... p){init(t,p...);}

  operator const string(){return o.str();}

private:
  ostringstream o;
  void init(){}
  template<typename T, typename ...P>
  void init(T t, P... p);
};

template<typename T, typename ...P>
void Mystrcat::init(T t, P ...p){
  o << t << ' ';
  init(p...);
}
int main(){
  int x;
  cin >> x;
  if (!x) throw runtime_error(Mystrcat("The value you entered is", x, "but non zero value expected", "error from file:", __FILE__, "line no:",__LINE__));
}
The above code uses variadic templates, which is a feature of C++0x. Hence to use the above code, one should select the appropriate compiler flag to include C++0x features. In the case linux, the compiler flag is: -std=c++0x
To see an implementation of the above without using classes, look at this usenet post. A similar implementation is available here.
About these ads

Responses

  1. [...] The header file “mystrcat.h” included in the following code is described here [...]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: