Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 317
Tomáš Zato - Reinstate Monica Avatar asked Jan 07 '23 16:01

Tomáš Zato - Reinstate Monica


1 Answers

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.

like image 144
Captain Obvlious Avatar answered Jan 16 '23 00:01

Captain Obvlious