std::compare_three_way
来自 cppreference.cn
定义于头文件 <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 // Although the comparison X <=> Y will work, a direct call // to std::compare_three_way{}(X, Y) requires the operator== // be defined, to satisfy the 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 的受限函数对象 (类) |