Are fold expressions subject to short-circuiting?

送分小仙女□ 提交于 2019-12-04 03:45:22

问题


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_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.




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!