首页 > 解决方案 > 如何在带有初始化程序的构造函数中使用 vprintf/cstdarg 功能?

问题描述

我想创建一个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,但我怎样才能将它与初始化语法结合起来呢?

标签: c++constructorvariadic-functions

解决方案


使用可变参数模板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...) ) 
         {
         }
};

完整示例


推荐阅读