[英]Does variadic template function call lambda parameter in reverse order?
The below demo prints 21
instead of 12
. 下面的演示打印21
而不是12
。 Why? 为什么?
#include <iostream>
template<class... F> void callMany(F... fib){
[&](...){}(
(fib(),123)...
);
}
int main()
{
auto f1=[&](){std::cout<<"1";};
auto f2=[&](){std::cout<<"2";};
callMany(f1,f2);
}
I tested it with both vc++ and g++. 我用vc ++和g ++对其进行了测试。 Both result are the same. 两者的结果是相同的。
Is it a standard behavior? 这是标准行为吗? If so, which rules, and why? 如果是这样,有哪些规则,为什么?
Does it depend on compiler? 它取决于编译器吗?
There is a way to reverse it, but I think it is a bit unrelated. 有一种方法可以逆转它,但我认为这有点无关。
When an expression that contains a pack expansion is evaluated, the pack is expanded first---which simply instantiates the code, so to speak, without performing any evaluation---then the resulting expression is evaluated according to the usual rules. 当评估包含包扩展的表达式时,首先扩展包-可以简单地实例化代码,可以说,无需执行任何评估-即可根据通常的规则对结果表达式进行评估。 Your expression 你的表情
[&](...){}(
(fib(),123)...
);
is expanded into 扩展为
[&](...){}(
(f1(),123), (f2(),123)
);
and since function arguments are evaluated in an unspecified order, you cannot rely on f2
being called before f1
or vice versa. 并且由于函数参数是按未指定的顺序求值的,因此您不能依赖于在f1
之前调用f2
, 反之亦然。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.