In C++17, are fold expressions subject to short-circuiting when used with &&
or ||
as their operator? If so, where is this specified?
In imperative language terms (notably C and C++), where side effects are important, short-circuit operators introduce a sequence point – they completely evaluate the first argument, including any side effects, before (optionally) processing the second argument.
Short-Circuit Evaluation: Short-circuiting is a programming concept in which the compiler skips the execution or evaluation of some sub-expressions in a logical expression. The compiler stops evaluating the further sub-expressions as soon as the value of the expression is determined.
The || OR operator is also a short-circuit operator. Since OR evaluates to true when one or both of its operands are true , short-circuit evaluation stops with the first true .
A fold expression is an instruction for the compiler to repeat the application of an operator over a variadic template pack. Let's take an example. A very basic one and with a questionable usefulness, but one that illustrates how fold expressions work.
Yes, fold expressions using &&
or ||
as the operator can short-circuit, subject to the usual caveat that it happens for the built-in meaning, but not for an overloaded operator function.
The meaning of a fold-expression is defined in [temp.variadic]/9:
The instantiation of a fold-expression produces:
((E_1
opE_2)
op ...)
opE_N
for a unary left fold,
E_1
op(
... op(E_N_minus_1
opE_N))
for a unary right fold,
(((E
opE_1)
opE_2)
op ...)
opE_N
for a binary left fold, and
E_1
op(
... op(E_N_minus_1
op(E_N
opE)))
for a binary right fold.In each case, op is the fold-operator,....
Since the instantiation of the fold-expression is in terms of an expression containing the operator, all the normal rules for the operator, including overload resolution, order of evaluation, and short-circuiting when a built-in operator, apply.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With