将可变参数模板参数传递给可变函数 [英] Passing variadic template arguments to a variadic function

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

问题描述

我们正在使用第三方C库,该库提供 printf()风格的日志功能,

We are using a third-party C library which provides a printf()-style log function,

void log(const char *format, ...);

出于不值得讨论的原因,我们需要限制邮件的接收速率已记录,类似

For reasons that aren't worth going in to, we need to limit the rate at which messages get logged, something along the lines of

void rate_limited_log(const char* format, ...)
{
    if (<not too fast>) {
         log(format, ...);
    }
}

幸运的是,C库的作者知道它们是什么

Fortunately the authors of the C library knew what they were doing, and provided

void logv(const char* format, va_list ap);

所以编写上面的函数是一个相对简单的事情。不幸的是,各种函数不能很好地与内联一起使用,所以我想出了第二个解决方案:

so writing the above function is a relatively simple matter. Unfortunately however variadic functions don't play well with inlining, and so I came up with a second solution:

template <typename... T>
void rate_limited_log(const char* format, T&&... args)
{
    if (<not too fast>) {
        log(format, std::forward<T>(args)...);
    }
}

这很完美,并且在我们限制速率的情况下想要。但是我对此有一些疑问:

This works perfectly and inlines the rate limiting condition as we'd like. But I have a couple of questions about it:


  • 正在将参数包扩展为C风格的可变参数调用是在C ++ 11中做的合法的,定义明确的事情,还是让我们很幸运能做到这一点?

  • Is expanding a parameter pack into a C-style variadic function call like this a legal, well-defined thing to do in C++11, or have we just got lucky that it works?

& 和 std :: forward 。如果我使用 const T& 或什至只是 T 值(无论是否使用)都似乎同样有效 std :: forward

Are the && and std::forward actually necessary here, given we're calling a C function? It seems to work just as well if I use const T&, or even just T by value, with or without std::forward.

推荐答案

将参数包扩展到varargs中是有效的。

Expanding parameter packs into varargs is valid.

当您要转发时,转发没有任何危害。但是,使用 const& 也会传达一些有用的信息。

And there is no harm in forwarding when you want to forward. But taking by const& also communicates something useful.

将值传递给。 。将经历默认参数提升。参见 http://en.cppreference.com/w/cpp/language/variadic_arguments

The values passed to ... will experience "default argument promotions". See http://en.cppreference.com/w/cpp/language/variadic_arguments

这些都不关心引用。

您可以改进代码。您可以通过种类以及通过实际解析格式字符串和确认数字来检查 Ts ... 是传递给打印例程的有效类型。有时是类型)。如果失败,则可以记录一条错误消息而不是崩溃。

You can improve your code. You can check that the Ts... are valid types to pass to the printing routine, both by "kind of type" and by actually parsing the formatting string and confirming number (and sometimes type) of arguments. If this fails, you can log an error message instead of crashing.

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

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