使varargs异常构造函数填充stringstream [英] Make varargs Exception constructor to fill stringstream
问题描述
基本上我正在做Exception类,我想要能够很容易地传递调试细节,例如:
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,'.');
}
这将需要 MyException
类接受可以由 stringstream
处理的varargs参数。我不知道我该怎么做,我想象是这样:
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();
}
推荐答案
当扩展参数包这样做。这里是魔法。
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.
这篇关于使varargs异常构造函数填充stringstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!