问题
In C++17, are fold expressions subject to short-circuiting when used with && or || as their operator? If so, where is this specified?
回答1:
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_1opE_2)op ...)opE_Nfor a unary left fold,
E_1op(... op(E_N_minus_1opE_N))for a unary right fold,
(((EopE_1)opE_2)op ...)opE_Nfor a binary left fold, and
E_1op(... op(E_N_minus_1op(E_NopE)))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.
回答2:
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.
来源:https://stackoverflow.com/questions/50111274/are-fold-expressions-subject-to-short-circuiting