可变参数模板参数包转发中的语法差异 [英] Syntax differences in variadic template parameter pack forwarding
问题描述
在使用可变参数模板时,我遇到了两种不同的方式来编写对 std :: forward
的调用,但是我想知道两者之间的实际区别是什么
While working with variadic templates I have come across two different ways of writing a call to std::forward
, but I am left wondering what the actual difference between the two syntaxes?
template<typename... T>
void one(T&&... args)
{
foo(std::forward<T&&...>(args...));
}
template<typename... T>
void two(T&&... args)
{
foo(std::forward<T&&>(args)...);
}
根据我的编译器,这些都是有效的语法,在大多数情况下,编译器不抱怨。但是我发现在某些情况下,一个或另一个是正确的,但是编译器没有详细说明为什么。
According to my compilers these are both valid syntax, and in most cases the compiler does not complain. But I have found some cases where one or the other is correct but the compiler does not say why in detail.
一个比另一个更正确吗?
它们的用途不同吗?
Is one more correct that the other?
Do they serve different purposes?
推荐答案
...
位置告诉编译器在哪里扩展包,对于它之前的东西中的每个元素一次(很难表达,但是我将在下面说明)。
The ...
placement tells the compiler where to expand the pack, once for each element in the thing before it (hard to phrase easily but I'll illustrate below).
让我们考虑一下一包 T = {int,double,char}
和 args = {1,2.0,'3'}
Let's consider a pack T = {int, double, char}
and args = {1, 2.0, '3'}
第一个示例(一个
)将在其中扩展 T
<>
然后在()$ c内的
args
$ c>变成
Your first example (one
) will expand T
inside of the <>
and then args
inside of the ()
so it becomes
foo(std::forward<T&&...>(args...)); // becomes:
foo(std::forward<int&&, double&&, char&&>(1, 2.0, '3'));
这不是 std :: forward
的方式有效,因为它只需要一个参数。您的第二个示例( two
)表示将整个调用扩展到 std :: forward
一次,用于包装中的每个项目,这样就变成了
This is not how std::forward
works since it only expects one argument. Your second example (two
) says to expand the whole call to std::forward
once for each item in the packs, so it becomes
foo(std::forward<T&&>(args)...); // becomes:
foo(std::forward<int&&>(1), std::forward<double&&>(2.0),std::forward<char&&>('3'));
至于为什么两个都编译良好,如果只调用一个参数,结果是相同的。如果您从未调用过它,那么它将不会被实例化。
As for why these both compiled fine, the result is identical if you called with only one argument. If you never called it at all then it wouldn't be instantiated.
这篇关于可变参数模板参数包转发中的语法差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!