如何使用太空飞船< =>具有StrCMP样式功能的操作员?

发布于 2025-01-21 20:04:05 字数 690 浏览 0 评论 0原文

假设我有一个带有struct cat的C库,并且一个函数比较(cat a,cat b),该根据以下规则返回整数: -

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

我正在编写C ++包装器(Say Catxxct作为C结构成员),并希望使用新的C ++ 20 SpaceShip操作员。

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. 如果我必须使用自定义而不是compare(),该怎么办?
  2. 运算符的返回类型到底是什么?
  3. fear__erding,部分订购等是什么意思?

Suppose I have a C library with a struct cat, and a function compare(cat a, cat b) which returns an integer according for following rules :-

  • if a < b then returns -1
  • if a = b then returns 0
  • if a > b then returns +1

I am writing c++ wrapper (say catxx, with ct as C struct member) for this library and would like to use the new C++20 spaceship operator.

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 ?*/;
}

How would I do this ? I am unable to understand the ordering concept.

  1. What if I had to use custom if else instead of compare() ?
  2. What exactly is return type of operator<=> ?
  3. What do weak_ordering, partial ordering etc. mean ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清旖 2025-01-28 20:04:05

来自 cppreference

三向比较操作员表达式具有表格

  lhs&lt; =&gt; RHS
 

表达式返回一个对象,使得

  • (a&lt; =&gt; b)&lt; 0如果lhs&lt; RHS
  • (a&lt; =&gt; b)&gt; 0如果lhs&gt; RHS
  • (a&lt; =&gt; b)== 0如果lhsrhs是等于/等效的。

因此,您可以简单地做到这一点

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

,因为操作数是整体类型,操作员会产生 std :: strong_ordering

From 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.

So you can just simply do

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

Since the operands are integral type, the operator yields a prvalue of type std::strong_ordering.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文