【发布时间】:2021-04-04 14:54:31
【问题描述】:
与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:我知道自定义<=> 不会生成默认==,因为== 可能以比使用<=> 更优化的方式实现,并且人们不希望低效的默认设置是生成。
【问题讨论】:
标签: c++ c++20 spaceship-operator