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

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

我想制作一个扩展 std::runtime_error 的 class MyException,异常消息具有 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...) ) 
         {
         }
};

Full example