boost::format with variadic template arguments

后端 未结 3 1364
隐瞒了意图╮
隐瞒了意图╮ 2021-01-12 03:37

Suppose I have a printf-like function (used for logging) utilizing perfect forwarding:

template
void awesome_printf         


        
3条回答
  •  失恋的感觉
    2021-01-12 04:20

    As is usual with variadic templates, you can use recursion:

    std::string awesome_printf_helper(boost::format& f){
        return boost::str(f);
    }
    
    template
    std::string awesome_printf_helper(boost::format& f, T&& t, Args&&... args){
        return awesome_printf_helper(f % std::forward(t), std::forward(args)...);
    }
    
    template
    void awesome_printf(std::string const& fmt, Arguments&&... args)
    {
        boost::format f(fmt);
    
        auto result = awesome_printf_helper(f, std::forward(args)...);
    
        // call BlackBoxLogFunction with result as appropriate, e.g.
        std::cout << result;
    }
    

    Demo.


    In C++17, simply (f % ... % std::forward(args)); will do.

提交回复
热议问题