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__));
}
-std=c++0x
[...] The header file “mystrcat.h” included in the following code is described here [...]
By: A C++ implementation of k-fold cross validation « Lokah Samastha Sughino Bhavantu on August 24, 2011
at 10:24 pm