oz1cz oz1cz - 10 months ago 72
C++ Question

Folding expressions in C++17

According to N4295 C++17 will allow me to calculate the sum of an unknown number of arguments thus:

template<typename ... T>
int sum(T...t)
return (... + t);

The document further states that I could use operators such as == or > instead of +. Can anybody come up with a sensible example of when I would want to use == or > in such a construct?

(I realize that people can define == and > to do strange things to strange classes, but surely that violates good practice. Writing
a > b > c > d
is hardly ever a good idea, is it?)


I would be an interesting feature if chained comparisons where handled like in Python where a < b < c is interpreted as a < b and b < c with a single evaluation of b. Unfortunately, this is not the case in C++ and even in strange cases, folding comparison operators indeed hardly makes sense.

Note that there was a proposal (P0313) to actually remove the operators ==, !=, <, >, <= and >= from the operators handled by fold expressions altogether. It has been discussed during the June 2016 committee meeting in Oulu. The motivation for the removal was rather brief:

Comparison operators don't make much sense in fold-expressions; they expand into expressions that have surprising effects, and are thus useful for dsl-metaprogrammers only. [...] It would be nice to be able to fix expressions like a < b < c. That would require a time machine. Not repeating the problem for fold-expressions seems doable.

That said the proposal was rejected.