C++20 default equality / inequality

Viewed 220

C++20 gives us the spaceship operator and even allows us to default it, generating all comparisons with default semantics, which will remove a lot of boilerplate from our code bases, great!

But how about equality and inequality? Does C++20 also give us a way to default equality and inequality? According to cppreference.com, defaulting spaceship will only give us < <= >, and >=, but not == and !=. Given that I usually need equality/inequality way more often than greater/less, this seems to be quite unfortunate. So, is there a way to also (or only) default generate == and != in C++20?

Update: The page now contains a description for defaulting operator==. Seems that I accessed the page like two hours before the documentation for this was added. :D

1 Answers

Does C++20 also give us a way to default equality and inequality?

Yes (but see the last paragraph). The syntax is same:

friend bool operator==(const T&, const T&) = default;
friend bool operator!=(const T&, const T&) = default; // not needed if == exists

The ordered inequality can be defaulted also:

friend bool operator<=(const T&, const T&) = default;
// ...

defaulting spaceship will only give us < <= >, and >=, but not == and !=

This is inaccurate. Defaulting three way comparison gives us all comparisons So, the above are not needed in that case.

Related