When overloading comparison operators for a type that can be ordered linearly, I typically end up with something like this (example is of comparing poker hand types):
enum class HandType : char {
HIGH_CARD = 0,
PAIR = 1,
TWO_PAIR = 2,
SET = 3,
STRAIGHT = 4,
FLUSH = 5,
FULL_HOUSE = 6,
QUADS = 7,
STRAIGHT_FLUSH = 8,
ROYAL_FLUSH = 9
};
bool operator<(HandType hero, HandType vill) {
return static_cast<int>(hero) < static_cast<int>(vill);
}
bool operator>(HandType hero, HandType vill) {
return vill < hero;
}
bool operator==(HandType hero, HandType vill) {
return !(hero < vill) && !(hero > vill);
}
bool operator!=(HandType hero, HandType vill) {
return !(hero == vill);
}
bool operator>=(HandType hero, HandType vill) {
return hero > vill || hero == vill;
}
bool operator<=(HandType hero, HandType vill) {
return hero < vill || hero == vill;
}
Yet the only operator that really contains information is the less than operator, and the remaining are identical and copy-pasted for every enum class that I do not want to declare as a plain enum for the sake of type safety.
Is there any way to implicitly define the remaining 5 operators that are always defined in terms of the less than operator, or any other way to make this less verbose, especially with many different enum classes that each need comparison operators?