boost::format with variadic template arguments

后端 未结 3 1395
隐瞒了意图╮
隐瞒了意图╮ 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:25

    Just to summarize the void.pointer's solution and the hints proposed by Praetorian, T.C. and Jarod42, let me provide the final version (online demo)

    #include 
    #include 
    
    template
    std::string FormatArgs(const std::string& fmt, const Arguments&... args)
    {
        boost::format f(fmt);
        std::initializer_list {(static_cast(
            f % args
        ), char{}) ...};
    
        return boost::str(f);
    }
    
    int main()
    {
        std::cout << FormatArgs("no args\n"); // "no args"
        std::cout << FormatArgs("%s; %s; %s;\n", 123, 4.3, "foo"); // 123; 4.3; foo;
        std::cout << FormatArgs("%2% %1% %2%\n", 1, 12); // 12 1 12
    }
    

    Also, as it was noted by T.C., using the fold expression syntax, available since C++17, the FormatArgs function can be rewritten in the more succinct way

    template
    std::string FormatArgs(const std::string& fmt, const Arguments&... args)
    {
        return boost::str((boost::format(fmt) % ... % args));
    }
    

提交回复
热议问题