折叠表达式短路

编程入门 行业动态 更新时间:2024-10-13 08:23:00
本文介绍了折叠表达式短路的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是一个自我触发的问题,基于我在此处给出的自我回答.

This is a self triggered question based on a self-answer I gave here.

这似乎很有说服力,说明了为什么折叠表达式,以及将fold表达式包装在带有可变参数的函数中的事实似乎不是短循环的(事实上,答案解释说,是在函数体内发生短路之前,函数调用触发了所有参数的求值).

This seems a pretty convincing explanation of why short-circuiting of logical operators is available in fold expressions, and of the fact that wrapping a fold expression in a function with a variadic argument seems to be non short-circuting (in fact, the answer explains, it's the function call which triggers the evaluation of all arguments, before the short-circuit can take place inside the function body).

但是,以下代码在我看来证明(至少当fold表达式中的参数为2时)不会发生短路:

However, the following code seems to me, proves that (at least when the arguments in a fold expression are 2) the short-circuiting doesn't happen:

#include <assert.h> #include <optional> constexpr auto all_r = [](auto const& ... ps){ return [&ps...](auto const& x){ return (ps(x) && ...); }; }; constexpr auto all_l = [](auto const& ... ps){ return [&ps...](auto const& x){ return (... && ps(x)); }; }; constexpr auto has_value = [](std::optional<int> o){ return o.has_value(); }; constexpr auto has_positive = [](std::optional<int> o){ assert(o.has_value()); return o.value() > 0; }; int main() { assert(!(has_value(std::optional<int>{}) && has_positive(std::optional<int>{}))); //assert(!(has_positive(std::optional<int>{}) && has_value(std::optional<int>{}))); // expectedly fails at run-time assert(!all_r(has_value, has_positive)(std::optional<int>{})); assert(!all_l(has_value, has_positive)(std::optional<int>{})); // I expected this to fail at run-time //assert(!all_r(has_positive, has_value)(std::optional<int>{})); //assert(!all_l(has_positive, has_value)(std::optional<int>{})); // I expected this to succeed at run-time }

推荐答案

...&&带有四个谓词 a,b,c,d 的ps(x)扩展为

... && ps(x) with four predicates a, b, c, d expands to

( ( a(x) && b(x) ) && c(x) ) && d(x)

这导致以下评估顺序: a b c d

which leads to this order of evaluation: a b c d

ps(x)&&... 扩展为

a(x) && ( b(x) && ( c(x) && d(x) ) )

这将导致相同的评估顺序: a b c d

which leads to the same order of evaluation: a b c d

这对短路没有任何改变;一旦错误,评估就会停止.

This does not change anything about short-circuiting; as soon as one is false, the evaluation stops.

更多推荐

折叠表达式短路

本文发布于:2023-11-12 10:28:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581226.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!