加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么左折叠表达式不会反转右折叠表达式的输出?

发布时间:2020-12-16 06:02:34 所属栏目:百科 来源:网络整理
导读:我正在看一下C 17 fold expressions,我想知道为什么以下程序输出 4 5 6 4 5 6 对于两个for_each调用 templatetypename F,typename... Tvoid for_each1(F fun,T... args){ (fun (std::forwardT(args)),...);}templatetypename F,typename... Tvoid for_each2(
我正在看一下C 17 fold expressions,我想知道为什么以下程序输出
4 5 6 
4 5 6

对于两个for_each调用

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; },6);
}

Live Example

我认为第二个折叠表达式是为了以相反的顺序输出数字

6 5 4

结果如何相同?

解决方法

根据§14.5.3 / 9

The instantiation of a fold-expression produces:

(9.1) — ((E1 op E2) op · · · ) op EN for a unary left fold,

(9.2) — E1 op (· · · op (EN-1 op EN )) for a unary right fold,

(9.3) — (((E op E1) op E2) op · · · ) op EN for a binary left fold,and

(9.4) — E1 op (· · · op (EN-1 op (EN op E))) for a binary right fold

In each case,op is the fold-operator,N is the number of elements in the pack expansion parameters,and each Ei is generated by instantiating the pattern and replacing each pack expansion parameter with its ith element.

在上面的代码中,它们是一元折叠表达式,它们的扩展是

template<typename F,T&&... args) {

    // Unary right fold (fun(args_0),(fun(args_1),(fun(args_2),...)))
    (fun (std::forward<T>(args)),T&&... args) {

    // Unary left fold ((fun(args_0),fun(args_1)),fun(args_2)),...
    (...,fun (std::forward<T>(args))); 
}

所以表达式具有与comma operator定义的相同的评估顺序,因此输出相同.

信用:感谢我的朋友Marco首先提出了原来的问题,并让我有机会解决这个潜在的误导性问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读