折叠表达式短路 [英] Short circuiting in fold expressions

查看:62
本文介绍了折叠表达式短路的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

似乎很有说服力,说明了为什么

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.

这篇关于折叠表达式短路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆