假设我有一个带有结构 cat
的 C 库和一个函数 compare(cat a, cat b)
,它根据以下规则返回一个整数:-
- 如果 a < b 则返回 -1
- 如果 a = b 则返回 0
- 如果 a > b 则返回 +1
我正在为这个库编写 c++ 包装器(比如 catxx
,ct
作为 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 ?*/;
}
我该怎么做?我无法理解订购概念。
- 如果我必须使用自定义
if else
而不是compare()
怎么办? - 究竟什么是运算符的返回类型<=>?
- weak_ordering、偏序等是什么意思?
最佳答案
来自 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.
所以你可以简单地做
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/