如何在带有初始值设定项的构造函数中使用 vprintf/cstdarg 功能?

How to use vprintf/cstdarg features in a constructor with initializers?

本文关键字:构造函数 vprintf 功能 cstdarg      更新时间:2023-10-16

我想做一个类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...) ) 
{
}
};

完整示例