Create a varargs exception constructor to populate stringstream

Basically, I am making an Exception class, and I want to be able to easily pass debugging data, for example:

var error = someFunction();
if(error!=0) {
    throw MyException("someFunction ended with error state #",error,'.');
}

This will require the class to MyExceptionaccept varargs arguments that can be processed stringstream. I have no idea how exactly I can do this, what I think about it:

#include <string>
#include <sstream>
template /* MUCH DEEP MAGIC HERE**/
MyException::MyException(/* MOAR DEEP MAGIC!!! **/) {
    std::stringstream ss;
    for(/** ITERATE THROUGH MORE MAGIC**/) {
        ss<</**FETCH MAGIC STUFF**/;
    }
    this->message = ss.str();
}
+4
source share
1 answer

You can abuse the comma operator when expanding the parameter package to do this. That's such magic.

template<typename Stream, typename ...Args>
Stream& print(Stream& o, const Args&... args)
{
    auto x = { ((o << args), 0)... };
    return o;
}

This sends all the arguments to the stream one at a time, taking the result of the expression after the decimal point, creating a list of integer initializers.

+9
source

All Articles