简体   繁体   English

如何在满足条件时停止折叠表达式 function 在中间调用并返回该值?

[英]How to stop fold expression function calls in the middle when a condition is met and return that value?

I have functions foo , bar , baz defined as follows:我有函数foobarbaz定义如下:

template <typename ...T>
int foo(T... t)
{
   return (bar(t), ...);
}

template <typename T>
int bar(T t)
{
    // do something and return an int
}

bool baz(int i)
{
    // do something and return a bool
}

I want my function foo to stop folding when baz(bar(t)) == true and return the value of bar(t) when that happens.我希望我的 function foobaz(bar(t)) == true时停止折叠,并在发生这种情况时返回bar(t)的值。 How can I modify the above code to be able to do that?我怎样才能修改上面的代码才能做到这一点?

Use short circuit operator && (or operator || ):使用短路operator && (或operator || ):

template <typename ...Ts>
int foo(Ts... t)
{
    int res = 0;
    ((res = bar(t), !baz(res)) && ...);
    // ((res = bar(t), baz(res)) || ...);
    return res;
}

Demo演示

Note:笔记:
(baz(res = bar(t)) ||...); would even be shorter, but less clear IMO.甚至会更短,但不太清楚 IMO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM