这是一个自我触发的问题,基于我在此处给出的自我回答.
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.
更多推荐
折叠表达式短路
发布评论