Search⌘ K
AI Features

User-defined and Auto-generated Comparison Operators

Explore the interaction between user-defined and compiler-generated comparison operators in C++20, focusing on the spaceship operator's auto-generation process and operator precedence rules to write cleaner and more efficient comparison code.

We'll cover the following...

When you can define one of the six comparison operators and also auto-generate all of them using the spaceship operator, there is one question: Which one has the higher priority? For example, the implementation MyInt has a user-defined less than and equal to operator and also the compiler-generated six comparison operators. Let’s see what happens.

C++
#include <compare>
#include <iostream>
class MyInt {
public:
constexpr explicit MyInt(int val): value{val} { }
bool operator == (const MyInt& rhs) const {
std::cout << "== " << '\n';
return value == rhs.value;
}
bool operator < (const MyInt& rhs) const {
std::cout << "< " << '\n';
return value < rhs.value;
}
auto operator<=>(const MyInt& rhs) const = default;
private:
int value;
};
int main() {
MyInt myInt2011(2011);
MyInt myInt2014(2014);
myInt2011 == myInt2014;
myInt2011 != myInt2014;
myInt2011 < myInt2014;
myInt2011 <= myInt2014;
myInt2011 > myInt2014;
myInt2011 >= myInt2014;
}

To see the user-defined == and < operator in action, I ...