std::compare_three_way
來自 cppreference.com
定義於標頭檔案 <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 的受限函式物件 (類) |