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

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

假设我有一个带有结构 cat 的 C 库和一个函数 compare(cat a, cat b),它根据以下规则返回一个整数:-

  • 如果 a < b 则返回 -1
  • 如果 a = b 则返回 0
  • 如果 a > b 则返回 +1

我正在为这个库编写 c++ 包装器(比如 catxxct 作为 C 结构成员),并希望使用新的 C++20 宇宙飞船运算符。

bool operator == (catxx& a, catxx& b)
{
    return !compare(a.ct, b.ct);
}

auto operator <=> (catxx& a, catxx& b)
{
    int result = compare(a.ct, b.ct);
    return /*what ?*/;
}

我该怎么做?我无法理解订购概念。

  1. 如果我必须使用自定义 if else 而不是 compare() 怎么办?
  2. 究竟什么是运算符的返回类型<=>?
  3. weak_ordering、偏序等是什么意思?

最佳答案

来自 cppreference :

The three-way comparison operator expressions have the form

lhs <=> rhs

The expression returns an object such that

  • (a <=> b) < 0 if lhs < rhs
  • (a <=> b) > 0 if lhs > rhs
  • (a <=> b) == 0 if lhs and rhs are equal/equivalent.

所以你可以简单地做

auto operator <=> (catxx& a, catxx& b)
{
  return compare(a.ct, b.ct) <=> 0;
}

由于操作数是整数类型,因此运算符产生类型为 std::strong_ordering 的纯右值.

关于c++ - 如何使用带有 strcmp 样式函数的 spaceship <=> 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71895283/

相关文章:

c++ - 如何在 C++ 的另一个模板函数中使用属于模板类的嵌套类型?

c++ - 在 `[likely]]` 语句中正确使用 C++20/`[[unlikely]]` `switch`

c++ - 为什么 `ranges::view::for_each` 要求仿函数必须返回 `InputRange` 概念的模型?

c++ - 在没有枚举和开关的情况下调用许多 vector 之一的函数

c++ - 三向比较运算符的顺序推导不一致

c++ - 我的模板语法有什么问题?

macos - 为什么 Xcode 与 Target 成员资格不匹配?

c++ - 将三路比较运算符的结果与 nullptr 进行比较有什么作用?

javascript - Javascript 中的组合比较/"Spaceship"运算符 (<=>)?

c++ - 使用 Boost 条件变量的死锁;指针不在线程之间更新?