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

loc*_*e14 3 c++ templates fold-expression c++17

我的函数foo, bar,baz定义如下:

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
}
Run Code Online (Sandbox Code Playgroud)

我希望我的函数foo在折叠发生时停止折叠并返回折叠发生时baz(bar(t)) == true的值。bar(t)我怎样才能修改上面的代码才能做到这一点?

Jar*_*d42 7

使用短路operator &&(或operator ||):

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

演示

注意:
(baz(res = bar(t)) || ...);甚至会更短,但在我看来不太清楚。