Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use three-way comparison (spaceship op) to implement operator== between different types?

Simple Task: I have these two types

struct type_a{
   int member;
};

struct type_b{
   int member;
};

I want to use this new C++20 spaceship op that everyone says is so cool to be able to write type_a{} == type_b{}. I didn’t manage to do that. Even if I write operator<=> between them, I only ever can call type_a{} <=> type_b{}, but never a simple comparison. That confuses me as with a single class, the three-way comparison also defines all the others.

Alternative formulation? How to make it so that std::three_way_comparable_with<type_a, type_b> is true?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The premise of the question is wrong. You don’t use the three-way comparison operator (<=>) to implement ==: you use == to implement ==:

bool operator==(const type_a& a, const type_b& b) {
    return a.member == b.member;
}

The source of confusion is that there is one exception to this rule: if a type declares a defaulted <=> then it also declares a defaulted ==:

struct type_c {
    int member;
    auto operator<=>(type_c const&) const = default;
};

That declaration is equivalent to having written:

struct type_c {
    int member;
    bool operator==(type_c const&) const = default;
    auto operator<=>(type_c const&) const = default;
};

But it’s not the <=> that gives you ==: it’s still the ==, and only ==, that gives you ==.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading