c++ - Why doesn't a left fold expression invert the output of a right fold expression? -
i'm taking @ c++17 fold expressions , i'm wondering why following program outputs
4 5 6 4 5 6
for both of 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 << << std::endl; }, 4, 5, 6); std::cout << "-" << std::endl; for_each2([](auto i) { std::cout << << std::endl; }, 4, 5, 6); }
i thought second fold expression meant output numbers in reverse order
6 5 4
how come results same?
according § 14.5.3/9
the instantiation of fold-expression produces:
(9.1) — ((e1 op e2) op · · · ) op en unary left fold,
(9.2) — e1 op (· · · op (en-1 op en )) unary right fold,
(9.3) — (((e op e1) op e2) op · · · ) op en binary left fold, and
(9.4) — e1 op (· · · op (en-1 op (en op e))) binary right fold
in each case, op fold-operator, n number of elements in pack expansion parameters, , each ei generated instantiating pattern , replacing each pack expansion parameter ith element.
in code above they're both unary fold expressions , expansion is
template<typename f, typename... t> void for_each1(f fun, t&&... args) { // unary right fold (fun(args_0) , (fun(args_1) , (fun(args_2) , ...))) (fun (std::forward<t>(args)), ...); } template<typename f, typename... t> void for_each2(f fun, t&&... args) { // unary left fold ((fun(args_0) , fun(args_1)) , fun(args_2)) , ... (..., fun (std::forward<t>(args))); }
so expressions have same evaluation order defined comma operator , output same.
credits: friend marco raised original question in first place , gave me chance solve potentially-misleading issue.
Comments
Post a Comment