c++11 Variadic Printf performance

后端 未结 2 509
梦如初夏
梦如初夏 2020-12-05 11:50

variadic template is introduced in c++11. And I found the printf function can be replaced using it. However, cout is used in the implementation. I am wondering if it is poss

2条回答
  •  我在风中等你
    2020-12-05 12:19

    At GoingNative2012, Andrei Alexandrescu gave an implementation of a variadic safe_printf(). He uses a two-step approach. First, check the format specifiers; and second, normalize the arguments being passed. Because the implementation delegates to printf() with checked formatters and arguments, there is no std::cout in sight and hardly any runtime overhead (the exception path should not be taken often in regular code)

    Code summary:

    template 
    int safe_printf(const char * f, const Ts&... ts) 
    {
        check_printf(f, normalizeArg(ts)...);  // check format specifiers
        return printf(f, normalizeArg(ts)...); // output with clean arguments
    }
    
    void check_printf(const char * f) 
    {
        // checking is O(N) in length of format specifiers
        for (; *f; ++f) {
            if (*f != ’%’ || *++f == ’%’) continue;
            throw Exc("Bad format");
        }
    }
    
    // variadic check_print(const char*, T...) omitted, see slides
    
    template 
    typename enable_if::value, long>::type
    normalizeArg(T arg) 
    { 
        return arg; 
    }
    
    // more overloads for float, T* and std::string omitted, see slides
    

提交回复
热议问题