9

假设我有一个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());
}

(我没有编译这个,但我的真正功能遵循这个指南)

如何将可变参数“展开”到 boost::format 变量中f

4

3 回答 3

12

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

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;
}

演示


在 C++17 中,就(f % ... % std::forward<Arguments>(args));可以了。

于 2014-09-16T02:36:43.820 回答
11

我做了一些谷歌搜索,发现了一个有趣的解决方案:

#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);
}

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

于 2014-09-16T02:43:29.557 回答
10

简单总结一下void.pointer的解决方案以及PraetorianTCJarod42提出的提示,我提供最终版本(在线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
}

此外,正如 TC 所指出的,使用从 C++17 开始可用的折叠表达式语法,可以以更简洁的方式重写 FormatArgs 函数

template<typename... Arguments>
std::string FormatArgs(const std::string& fmt, const Arguments&... args)
{
    return boost::str((boost::format(fmt) % ... % args));
}
于 2017-09-08T19:41:46.613 回答