代码之家  ›  专栏  ›  技术社区  ›  anatolyg

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

  •  0
  • anatolyg  · 技术社区  · 6 年前

    我想上一节课 MyException 延伸到 std::runtime_error ,异常消息具有 printf 语法。我想这样用:

    int main()
    {
        int index = -1;
        if (index < 0)
            throw MyException("Bad index %d", index);
    }
    

    如何编写的构造函数 ?

    class MyException: public std::runtime_error
    {
        MyException(const char* format ...):
            runtime_error(what?)
    };
    

    我想我必须 va_list 打电话给 vprintf 但如何将其与初始化语法结合起来呢?

    1 回复  |  直到 6 年前
        1
  •  1
  •   anatolyg    6 年前

    使用可变模板 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