std:: compare_three_way
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Old binders and adaptors | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
定义于头文件
<compare>
|
||
|
定义于头文件
<functional>
|
||
|
struct
compare_three_way
;
|
(C++20 起) | |
用于执行比较的函数对象。可推导函数调用运算符的参数类型和返回类型。
目录 |
嵌套类型
| 嵌套类型 | 定义 |
is_transparent
|
未指定 |
成员函数
|
operator()
|
获取两个参数的三路比较结果
(公开成员函数) |
std::compare_three_way:: operator()
|
template
<
class
T,
class
U
>
constexpr auto operator ( ) ( T && t, U && u ) const ; |
||
给定表达式 std:: forward < T > ( t ) <=> std:: forward < U > ( u ) 为 expr :
-
-
在
实现定义的指针严格全序
中比较两个转换后的指针(类型为
P):
-
- 若 t 先于 u ,则返回 std::strong_ordering::less 。
- 若 u 先于 t ,则返回 std::strong_ordering::greater 。
- 否则返回 std::strong_ordering::equal 。
-
若从
T到P的转换序列或从U到P的转换序列不满足 等值保持性 ,则行为未定义。
-
在
实现定义的指针严格全序
中比较两个转换后的指针(类型为
- 否则:
-
- 返回 expr 的结果。
- 若 std:: three_way_comparable_with < T, U > 未建模,则行为未定义。
此重载仅当满足 std:: three_way_comparable_with < T, U > 时参与重载决议。
示例
#include <compare> #include <iostream> struct Rational { int num; int den; // > 0 // 虽然比较 X <=> Y 可以正常工作,但直接调用 // std::compare_three_way{}(X, Y) 需要定义 operator==, // 以满足 std::three_way_comparable_with 的要求。 constexpr bool operator==(Rational const&) const = default; }; constexpr std::weak_ordering operator<=>(Rational lhs, Rational rhs) { return lhs.num * rhs.den <=> rhs.num * lhs.den; } void print(std::weak_ordering value) { value < 0 ? std::cout << "less\n" : value > 0 ? std::cout << "greater\n" : std::cout << "equal\n"; } int main() { Rational a{6, 5}; Rational b{8, 7}; print(a <=> b); print(std::compare_three_way{}(a, b)); }
输出:
greater greater
缺陷报告
下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
| 缺陷报告 | 应用于 | 发布时的行为 | 正确行为 |
|---|---|---|---|
| LWG 3530 | C++20 | 比较指针时放宽了语法检查 | 仅放宽语义要求 |
参见
|
(C++20)
|
实现
x
==
y
的受约束函数对象
(类) |
|
(C++20)
|
实现
x
!
=
y
的受约束函数对象
(类) |
|
(C++20)
|
实现
x
<
y
的受约束函数对象
(类) |
|
(C++20)
|
实现
x
>
y
的受约束函数对象
(类) |
|
(C++20)
|
实现
x
<=
y
的受约束函数对象
(类) |
|
(C++20)
|
实现
x
>=
y
的受约束函数对象
(类) |