4

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 ?
0xB00B
  • 1,598
  • 8
  • 26
  • 1
    What portion(s) of [the FAQ on the spaceship operator and its usage](https://stackoverflow.com/q/47466358) are unclear to you? If you can clarify your question, we can provide better help. – Cody Gray - on strike Apr 16 '22 at 15:47

1 Answers1

7

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.

康桓瑋
  • 33,481
  • 5
  • 40
  • 90
  • This will not implement `operator==`. – Nicol Bolas Apr 16 '22 at 15:47
  • 2
    Isn't OP already implemented `operator==`? – 康桓瑋 Apr 16 '22 at 15:48
  • And what exactly is return type of this operator ? what if i had to use some custom logic instead of compare() ? – 0xB00B Apr 16 '22 at 15:49
  • 1
    For 2 integers `<=>` evaluates to a `std::strong_ordering`. You can use `std::strong_ordering::less`, `std::strong_ordering::equal` or `std::strong_ordering::greater` directly in your code like `if (a < b) return std::strong_ordering::less;`. – mch Apr 16 '22 at 15:57