与 this question 略有不同。我想用自定义 <=>
定义自定义类型运算符并使用该自定义 <=>
运算符生成 ==
。尝试以下操作
#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:我知道一个自定义<=>
不生成默认 ==
因为==
可能比使用 <=>
更优化地实现并且人们不希望生成低效的默认值。
最佳答案
I'm wondering if there's a better way to get == out of <=>.
不,没有。您所做的( return 0 == (lhs<=>rhs);
)是最佳方法。您还在寻找什么?
关于c++ - 生成使用非默认 <=> 的 == 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65467385/