In a slight variation of this question. I would like to define a custom type with a custom <=>
operator and use that custom <=>
operator to generate a ==
. Trying the following
#include <compare>
#include <iostream>
#include <cassert>
struct widget {
int member;
int non_comparison_data;
friend std::strong_ordering operator<=>(const widget& lhs,
const widget& rhs) {
std::cout << "doing a three way comparison" << std::endl;
return lhs.member <=> rhs.member;
}
// friend bool operator==(const widget& lhs, const widget& rhs) {
// return 0 == (lhs <=> rhs);
// }
friend bool operator==(const widget& lhs, const widget& rhs) = default;
};
int main() {
widget a{.member = 1, .non_comparison_data = 23};
widget b{.member = 1, .non_comparison_data = 42};
assert(a==b);
return 0;
}
I observe that a default ==
operator does not use the custom <=>
operator, but instead does what would be done in absence of any custom comparison and compares all data members. I can define an operator ==
on my own that uses <=>
like follows, but I'm wondering if there's a better way to get ==
out of <=>
.
friend bool operator==(const widget& lhs, const widget& rhs) {{
return 0 == (lhs <=> rhs);
}
PS: I'm aware a custom <=>
doesn't generate a default ==
because ==
is likely implementable in a more optimal way than using <=>
and one does not want an inefficient default to be generated.