jack
jack

Reputation: 1790

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';
}

Upvotes: 3

Views: 753

Answers (2)

madhur4127
madhur4127

Reputation: 336

As per @Silvio Mayolo's link: https://en.cppreference.com/w/cpp/language/default_comparisons

If operator<=> is defaulted and operator== is not declared at all, then operator== is implicitly defaulted.

Therefore in this definition:

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

operator== won't be implicitly declared, hence the compiler error.

Upvotes: 2

Sam Varshavchik
Sam Varshavchik

Reputation: 118425

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

Upvotes: 2

Related Questions