Search code examples
c++spaceship-operator

Define spaceship operator for simple struct


I am trying to explicitly implement the spaceship operator.

The following is a simple example which fails. What am I doing wrong? godbolt link

#include <iostream>

struct Foo {
    int value;

    // both work
    auto operator<=>(const Foo&) const = default;
    //bool operator==(const Foo other) const { return value == other.value; }

    // both fail
    // auto operator<=>(const Foo& other) const { return value <=> other.value; }
    // auto operator<=>(const Foo other) const { return value <=> other.value; }
};

// fails
//auto operator<=>(const Foo lhs, const Foo rhs) { return lhs.value <=> rhs.value; }

int main(){
    Foo x{0};
    std::cout << (x == x) << '\n';
}

Solution

  • operator<=> does not actually implement the == operator. operator== must be defined separately from operator<=>. So, you need to define operator== as well.

    The reason is that it's quite often possible to implement == more efficiently than <=>.