1

Does anyone know why I’m getting a compiler error for the equality operation on a class that has a 3 way operator override? I'm using VS 2019.

class Rectangle
{
public:
    constexpr Rectangle(const int width, const int height) :
        width{ width }, height{ height } { }

    auto operator<=>(const Rectangle& rhs) const {
        return width * height <=> rhs.width * rhs.height;
    }

    int width;
    int height;
};

void Test() {
    Rectangle r1(5, 10);
    Rectangle r2(10, 5);

    auto ret1 = r1 < r2;
    auto ret2 = r1 <= r2;
    auto ret3 = r1 == r2;  // error on this line but previous two are good
}

I'm getting an error for the line noted above: NativeConsoleApp.cpp(68,20): error C2676: binary '==': 'Rectangle' does not define this operator or a conversion to a type acceptable to the predefined operator

Edit: Note the explanation at non-defaulted operator <=> doesn't generate == and != in C++20 doesn't address why the inequality operators work but not the equality operator.

Edit: The link above makes sense now after rereading it a month later.

adamtki
  • 11
  • 2
  • 1
    (not an answer to your question) Beware your `operator<=>` implementation semantic : i doubt a `Rectangle{1,6}` should be considered equal to `Rectangle{2,3}` – limserhane Jan 06 '21 at 23:00
  • It's not a real world example. I just created the classes to understand how to use the spaceship operator. – adamtki Jan 06 '21 at 23:12
  • The answers very much *do* "address why the inequality operators work but not the equality operator"?? "If a class does something special in its three-way comparison, it will likely need to do something special in its `==`. Thus, instead of generating a non-sensible default, the language leaves it up to the programmer." "During the standardization of this feature, it was decided that equality and ordering should logically be separated. As such, uses of equality testing (`==` and `!=`) will never invoke `operator<=>`." – HTNW Jan 07 '21 at 06:25
  • Yes, you are correct. Reading it again a month later makes sense now. – adamtki Mar 03 '21 at 00:45

0 Answers0