名稱空間
變體
操作

std::compare_three_way

來自 cppreference.com
< cpp‎ | 工具
 
 
 
函式物件
函式呼叫
(C++17)(C++23)
恆等函式物件
(C++20)
透明運算子包裝器
(C++14)
(C++14)
(C++14)
(C++14)  
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)

舊繫結器和介面卡
(直到 C++17*)
(直到 C++17*)
(直到 C++17*)
(直到 C++17*)  
(直到 C++17*)
(直到 C++17*)(直到 C++17*)(直到 C++17*)(直到 C++17*)
(直到 C++20*)
(直到 C++20*)
(直到 C++17*)(直到 C++17*)
(直到 C++17*)(直到 C++17*)

(直到 C++17*)
(直到 C++17*)(直到 C++17*)(直到 C++17*)(直到 C++17*)
(直到 C++20*)
(直到 C++20*)
 
定義於標頭檔案 <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

  • 若從 TP 的轉換序列或從 UP 的轉換序列不保持相等,則行為未定義。
  • 否則

此過載僅當滿足 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 比較指標時放寬了語法檢查 僅放寬了語義要求

[編輯] 參閱

實現 x == y 的受限函式物件
(類) [編輯]
實現 x != y 的受限函式物件
(類) [編輯]
實現 x < y 的受限函式物件
(類) [編輯]
實現 x > y 的受限函式物件
(類) [編輯]
實現 x <= y 的受限函式物件
(類) [編輯]
實現 x >= y 的受限函式物件
(類) [編輯]