In C++17, are fold expressions subject to short-circuiting when used with &&
or ||
as their operator? If so, where is this specified?
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.
While @aschepler's answer is the specifically-correct one, I'd like to repeat a life-lesson I've shared regarding another fine technical point (tuple order of destruction):
If you can formulate, for multiple alternatives, a reasonable argument for why that alternative should be the one mandated by the standard - then you should not assume any of them is mandated (even if one of them happens to be).
In the context of fold expressions and short-circuit logic - it's already difficult enough to read variadic templated codel so I'd try saving the reader of my code the head-scratching regarding whether or not fold-short-circuiting happens...
If you can't avoid writing and
and or
folds, at least be generous with commenting regarding short-circuit behavior.
std::tuple
it is completely unspecified how the tuple elements are stored (are they data members of the tuple? data members of one or more base classes of the tuple? data members of some other data member of the tuple? Created using placement-new in untyped buffers of unsigned char
?!). So you can't conclude anything about the order of initialization. For fold expressions the standard specifies the precise form of the expanded expression, so the usual semantics of the relevant operator apply. –
Jenn © 2022 - 2024 — McMap. All rights reserved.