Implementing custom comparison logic using the spaceship operator <=>
in C++20 allows you to define how your custom types should be compared in a consistent and efficient manner. Here’s a step-by-step guide to implementing this:
First, define your custom type. For example, let’s create a Player
class that compares players based on their scores and, if the scores are the same, by their names.
#include <compare>
#include <iostream>
#include <string>
class Player {
public:
Player(std::string name, int score)
: Name{name}, Score{score} {}
std::strong_ordering operator<=>(
const Player& Other) const {
if (auto cmp = Score <=> Other.Score; cmp != 0) {
return cmp;
}
return Name <=> Other.Name;
}
bool operator==(const Player& Other) const {
return Score == Other.Score && Name == Other.Name;
}
std::string Name;
int Score;
};
int main() {
Player Player1{"Alice", 10};
Player Player2{"Bob", 10};
Player Player3{"Alice", 20};
if (Player1 < Player2) {
std::cout << Player1.Name
<< " is ranked lower than "
<< Player2.Name << "\n";
}
if (Player1 > Player3) {
std::cout << Player1.Name
<< " is ranked higher than "
<< Player3.Name << "\n";
}
if (Player1 == Player1) {
std::cout << Player1.Name
<< " is equal to "
<< Player1.Name << "\n";
}
}
Alice is ranked lower than Bob
Alice is equal to Alice
In the operator<=>
, we first compare the scores. If they are not equal, we return the result of that comparison.
If the scores are equal, we then compare the names. This secondary comparison ensures that players with the same score are ordered by their names.
You can now use all the comparison operators with your custom type. The <=>
operator handles the ordering, and the ==
operator ensures that equality is checked correctly.
In this example, the comparison logic considers both the Score
and Name
fields of the Player
class, demonstrating how you can implement and use custom comparison logic effectively with the spaceship operator in C++20.
Answers to questions are automatically generated and may not have been reviewed.
A guide to simplifying our comparison operators using C++20 features