我有函数 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
}
我想要我的函数 foo
baz(bar(t)) == true
时停止折叠并返回 bar(t)
的值当这种情况发生时。我怎样才能修改上面的代码才能做到这一点?
最佳答案
使用短接operator &&
(或operator ||
):
template <typename ...Ts>
int foo(Ts... t)
{
int res = 0;
((res = bar(t), !baz(res)) && ...);
// ((res = bar(t), baz(res)) || ...);
return res;
}
注意:
(baz(res = bar(t)) || ...);
甚至会更短,但不太清楚 IMO。
关于c++ - 满足条件时如何在中间停止折叠表达式函数调用并返回该值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70184436/