Home > Blockchain >  Define spaceship operator for simple struct
Define spaceship operator for simple struct

Time:12-18

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related