Search code examples
c++c++17foldshort-circuiting

Are fold expressions subject to short-circuiting?


In C++17, are fold expressions subject to short-circuiting when used with && or || as their operator? If so, where is this specified?


Solution

  • 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 op E_2) op ...) op E_N for a unary left fold,

    • E_1 op (... op (E_N_minus_1 op E_N)) for a unary right fold,

    • (((E op E_1) op E_2) op ...) op E_N for a binary left fold, and

    • E_1 op (... op (E_N_minus_1 op (E_N op E))) 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.