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

标签 c++ templates c++17 fold-expression

我有函数 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;
}

Demo

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

关于c++ - 满足条件时如何在中间停止折叠表达式函数调用并返回该值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70184436/

相关文章:

c++ - 支持阿拉伯语的 Qt 演示

c++ - 在boost managed_memory_segment中使用私有(private)构造函数构造对象

c++ - 为什么当我在 const 之前写 noexcept 时出现错误

c++ - 如何将文件系统路径转换为字符串

c++ - MFC 中的动态菜单

c++ - 如何从 C++ 中的推文中删除表情符号?

c++ - 将 std::integer_sequence 作为模板参数传递给元函数

c++ - 为什么 std::void_t 在这种情况下不起作用?

c++ - 如何使用模板链接数据结构中的节点对象?

C++ - 定义 2 个模板参数但仅调用 1 个