I'm taking a look at C++17 fold expressions and I'm wondering why does the following program outputs
4 5 6
4 5 6
for both of the for_each
calls
template<typename F, typename... T>
void for_each1(F fun, T&&... args)
{
(fun (std::forward<T>(args)), ...);
}
template<typename F, typename... T>
void for_each2(F fun, T&&... args)
{
(..., fun (std::forward<T>(args)));
}
int main()
{
for_each1([](auto i) { std::cout << i << std::endl; }, 4, 5, 6);
std::cout << "-" << std::endl;
for_each2([](auto i) { std::cout << i << std::endl; }, 4, 5, 6);
}
I thought that the second fold expression was meant to output the numbers in reverse order
6 5 4
How come the results are the same?
According to § 14.5.3/9
in the code above they're both unary fold expressions and their expansion is
so the expressions have the same evaluation order as defined by the comma operator and thus the output is the same.
Credits: thanks to my friend Marco who raised the original question in the first place and gave me the chance to solve this potentially-misleading issue.