Home > Back-end >  How to use spaceship <=> operator with strcmp style function?
How to use spaceship <=> operator with strcmp style function?

Time:04-17

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 ?

CodePudding user response:

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.

  • Related