我想做一个类MyException
来扩展std::runtime_error
,但异常消息具有printf
语法。我想这样使用它:
int main()
{
int index = -1;
if (index < 0)
throw MyException("Bad index %d", index);
}
如何为MyException
编写构造函数?
class MyException: public std::runtime_error
{
MyException(const char* format ...):
runtime_error(what?)
};
我假设我必须在某处放置va_list
和调用vprintf
,但是如何将其与初始化语法相结合?
将可变参数模板与sprintf
一起使用:
class MyException: public std::runtime_error {
char buf[200]; // One issue: what initial size of that?
template<class ... Args>
char* helper(Args ... args)
{
sprintf(buf, args...);
return buf;
}
public:
template<class ... Args>
MyException(Args ... args):
std::runtime_error( helper(args...) )
{
}
};
完整示例