使用可变参数模板参数的boost :: format

时间:2014-09-16 02:11:45

标签: c++ c++11 boost variadic-templates boost-format

假设我有一个类似printf的函数(用于记录),使用完美转发:

template<typename... Arguments>
void awesome_printf(std::string const& fmt, Arguments&&... args)
{
    boost::format f(fmt);
    f % /* How to specify `args` here? */;
    BlackBoxLogFunction(boost::str(f).c_str());
}

(我没有编译这个,但我的实际功能遵循本指南)

我怎样才能&#34;展开&#34; boost :: format变量f的可变参数?

3 个答案:

答案 0 :(得分:11)

与可变参数模板一样,您可以使用递归:

std::string awesome_printf_helper(boost::format& f){
    return boost::str(f);
}

template<class T, class... Args>
std::string awesome_printf_helper(boost::format& f, T&& t, Args&&... args){
    return awesome_printf_helper(f % std::forward<T>(t), std::forward<Args>(args)...);
}

template<typename... Arguments>
void awesome_printf(std::string const& fmt, Arguments&&... args)
{
    boost::format f(fmt);

    auto result = awesome_printf_helper(f, std::forward<Arguments>(args)...);

    // call BlackBoxLogFunction with result as appropriate, e.g.
    std::cout << result;
}

Demo


在C ++ 17中,只需(f % ... % std::forward<Arguments>(args));即可。

答案 1 :(得分:9)

我做了一些谷歌搜索并找到了一个有趣的解决方案:

#include <iostream>
#include <boost/format.hpp>

template<typename... Arguments>
void format_vargs(std::string const& fmt, Arguments&&... args)
{
    boost::format f(fmt);
    int unroll[] {0, (f % std::forward<Arguments>(args), 0)...};
    static_cast<void>(unroll);

    std::cout << boost::str(f);
}

int main()
{
    format_vargs("%s %d %d", "Test", 1, 2);
}

我不知道这是否是推荐的解决方案,但似乎有效。我不喜欢hacky static_cast用法,这似乎有必要使GCC上未使用的变量警告静音。

答案 2 :(得分:8)

只是总结一下void.pointer's solution和提议的提示by PraetorianT.C.Jarod42,让我提供最终版本(online demo

#include <boost/format.hpp>
#include <iostream>

template<typename... Arguments>
std::string FormatArgs(const std::string& fmt, const Arguments&... args)
{
    boost::format f(fmt);
    std::initializer_list<char> {(static_cast<void>(
        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
}

此外,使用as it was noted by T.C.语法的fold expression,自C ++ 17以来可用,FormatArgs函数可以用更简洁的方式重写

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