Make varargs Exception constructor to fill stringstream

青春壹個敷衍的年華 提交于 2019-12-21 05:21:16

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/32260642/make-varargs-exception-constructor-to-fill-stringstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!