带有可变参数模板参数的boost :: format [英] boost::format with variadic template arguments

查看:449
本文介绍了带有可变参数模板参数的boost :: format的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类似printf的功能(用于记录),它利用了完美的转发功能:

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

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?

How can I "unroll" the variadic argument into the boost::format variable f?

推荐答案

我进行了一次谷歌搜索,发现了一个有趣的解决方案:

I did some googling and found an interesting solution:

#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上未使用的变量警告保持沉默是必要的.

I don't know if this is a recommended solution but it seems to work. I don't like the hacky static_cast usage, which seems necessary to silence the unused variable warnings on GCC.

这篇关于带有可变参数模板参数的boost :: format的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆