c++ - 带有可变模板参数的 boost::format

标签 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());
}

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

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

最佳答案

只是总结 void.pointer's solution和建议的提示 by Praetorian , T.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));
}

关于c++ - 带有可变模板参数的 boost::format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25859672/

相关文章:

c++ - 重新检查时指针属性发生变化

c++ - 为什么在所有情况下都允许指向 shared_ptr 构造的原始指针?

c++ - 使用 boost::container 或 boost::recursive_wrapper 创建不完整类型的容器

c# - 将 boost::archive 写入 C# 流

java - 如何检查在 C++ 中使用的 Java 版本

c++ - 有没有用 C++ 编写的开源 PDF 打印机?

c++ - 关于多线程程序中的临时对象

c++ - 为什么类内初始化器只能使用 = 或 {}?

c++ - Node.js C++ 插件 : Threading

C++ boost::regex 倍数捕获