I want to find a method or macro which a <= b && b < c can rewrite as a <= b < c, because a <= b < c seems more straight forward and often seen in user requirement definition. Also a <= b && b < c needs to type b twice.

I searched about operators, but it seems (I think) only can add operation for custom class, but not alter the original operation. Also I know I can overload bool operator > but not sure I can add a new operation int operator > which returns the larger one. Also even operator overload works, a <= b < c will return c only, but not the true or false of statement a <= b < c (similar to MAX(c, MAX(b, a))).

Is there any method to simulate a <= b < c <= ...?

1

There are 1 answers

0
MSalters On

The comments already note it's a bad idea so I won't repeat that.

It's somewhat possible with macro's. None of those operators can be a macro name. But if you'd allow BADIDEA(a<=b<c), you can expand that as HelperClass()*a<=b<c. The idea is that Helperclass::operator* has the highest precendence. That means we parse it as HelperClass::operator*(HelperClass(), a).

This first part returns another HelperClass. HelperClass also overloads operator<= so we next get HelperClass::operator<=(firstExpr, b).

In this way, we can build a list of arguments passed to HelperClass It even supports BADIDEA(a<b<c<d). In the end, we just call HelperClass::operator bool which returns true if and only if the list of arguments is sorted.

ALternatively, you don't need to build the list of arguments, but can immediately evaluate them. HelperClass()*4<3 can already evaluate to false before you see <=7 in HelperClass()*4<3<=7