我想创建一个类 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...) )
{
}
};
关于c++ - 如何在带有初始值设定项的构造函数中使用 vprintf/cstdarg 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57841769/