c++ - 生成使用非默认 <=> 的 == 运算符

标签 c++ c++20 spaceship-operator

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:compiler-explorer link

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/

相关文章:

Visual Studio 中的 C++20 支持

c++ - 如何在表达式编译错误时将概念评估为 false

c++ - 如何使用带有 strcmp 样式函数的 spaceship <=> 运算符?

c++ - 三向比较运算符与减法有何不同?

c++ - 在 C++ : strange performance issue 中读取文件的奇特方式

c++ - 从 perl 更新 C++ 变量

c++ - 为什么 `std::ranges::clamp`会如此严格地限制投影数量?

perl - 什么时候在某种外部使用飞船运算符(operator)?

c++ - 复制构造函数并返回传递的参数

c++ - 简单的字符串问题