Search code examples
c++templatesstringstream

Make varargs Exception constructor to fill stringstream


Basically I am making Exception class and I want to be able to pass debug details easily, such as this:

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

This would require the MyException class to accept varargs arguments that can be processed by stringstream. I have no idea how exactly could I do that, what I imagine is this:

#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();
}

Solution

  • You can abuse the comma operator when expanding the parameter pack to do this. Here be that magic.

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

    This sends all arguments to the stream one at a time while taking the result of the expression after the comma constructing an initializer list of integers.