c++operator-overloadingc++20spaceship-operator

How to overload spaceship operator (<=>) with reversed order?


I'd like to implement operator<=> to a custom type Bar with a reversed ordering.

struct Bar
{
    auto operator<=>(const Bar& rhs) const
    {
        // How to implement <=> on `int i`
        // But with reversed order
        // i.e., Bar{1} > Bar{2}
        
        // This definitely does not work
        return !(a <=> rhs.a);
    }
    int i;
};

Is there simpler way than using a switch-case to enumerate all the cases?


Solution

  • The other answers already point out that if you want to reverse x <=> y than the answer is simply y <=> x. We can just make a table and verify this:

    x <=> y y <=> x
    x == y equal equal
    x < y less greater
    x > y greater less

    That's the easiest approach, just reverse the operands - since that's what you want to do, reverse the operation, by reversing the operands.

    Another approach, which is useful in the case where you don't have the operands but do have the result (which is less likely but does come up) is 0 <=> (x <=> y):

    x <=> y 0 <=> (x <=> y)
    equal equal
    less greater
    greater less

    Conceptually, you can think of <=> as returning -1, 0, or 1 (it doesn't, it returns a class type, but sometimes a small fiction helps us understand), so for instance you can think of 0 <=> less as basically doing 0 <=> -1 which is greater, and likewise 0 <=> greater as basically doing 0 <=> 1 which is less. You get the right answer, so as long as you don't fall into the trap of really thinking that these are ints and wanting to do more int math on them, you'll be fine.