问题描述
略有变化的 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:我知道自定义 <=>
不会生成默认 ==
,因为 ==
可能比使用 <=>
和一个更优的方式实现不希望生成低效的默认值。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)