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 :-
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.
if else
instead of compare()
?From cppreference:
The three-way comparison operator expressions have the form
lhs <=> rhs
The expression returns an object such that
(a <=> b) < 0
iflhs
<rhs
(a <=> b) > 0
iflhs
>rhs
(a <=> b) == 0
iflhs
andrhs
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
.