Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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';
}
like image 787
jack Avatar asked Sep 02 '25 17:09

jack


1 Answers

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

like image 135
Sam Varshavchik Avatar answered Sep 05 '25 06:09

Sam Varshavchik