在这个问题的轻微变化中。我想使用自定义运算符定义自定义类型,<=>并使用该自定义<=>运算符生成==. 尝试以下
#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;
}
我观察到默认==运算符不使用自定义<=>运算符,而是在没有任何自定义比较的情况下执行并比较所有数据成员。我可以自己定义一个==使用<=>如下的运算符,但我想知道是否有更好的方法来==摆脱<=>.
friend bool operator==(const widget& lhs, const widget& rhs) {{
return 0 == (lhs <=> rhs);
}
PS:编译器-资源管理器链接
PS:我知道自定义<=>不会生成默认值==,因为==它可能以比使用更优化的方式实现,<=>并且不希望生成低效的默认值。