1

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 <= ...?

o11c
  • 15,265
  • 4
  • 50
  • 75
ggrr
  • 7,737
  • 5
  • 31
  • 53
  • 3
    I think to most C++ programmers `a <= b < c` would look like a potential bug, because they are used to seeing `a<=b && b < c`. – rozina Jun 10 '15 at 06:12
  • 12
    The only way to distort the language that way is to overload the first operator to return an object that overload the next operator and so on. However I suggest you don't do that, because it might be obvious to you right now, but not to others, and that "others" might include yourself in a year. – Some programmer dude Jun 10 '15 at 06:13
  • 2
    http://stackoverflow.com/questions/12658124/how-to-implement-3-x-10-in-c/12658241 – Brent Bradburn Jun 10 '15 at 06:22
  • You might be able to write a macro like `COMPARE(a, <=, b, <, c)` but ugh. A template function `compare(a, cmp_le, b, cmp_lt, c)` would be easier ... – o11c Jun 10 '15 at 19:40

1 Answers1

0

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

MSalters
  • 173,980
  • 10
  • 155
  • 350