Namespaces
Variants

std:: compare_three_way

From cppreference.net
Utilities library
Function objects
Function invocation
(C++17) (C++23)
Identity function object
(C++20)
Old binders and adaptors
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
( until C++17* ) ( until C++17* )
( until C++17* ) ( until C++17* )

( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
定義済みヘッダー <compare>
定義済みヘッダー <functional>
struct compare_three_way ;
(C++20以降)

比較を実行するための関数オブジェクト。関数呼び出し演算子のパラメータ型と戻り値の型を推論します。

目次

ネストされた型

ネスト型 定義
is_transparent unspecified

メンバー関数

operator()
両方の引数に対する三方比較の結果を取得する
(public member function)

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 として与える:

  • T から P への変換シーケンス、または U から P への変換シーケンスが 等価性保存 でない場合、動作は未定義である。
  • それ以外の場合:

このオーバーロードは、 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++規格に対して遡及的に適用されました。

DR Applied to Behavior as published Correct behavior
LWG 3530 C++20 ポインタ比較時に構文チェックが緩和されていた 意味論的な要件のみが緩和される

関連項目

x == y を実装する制約付き関数オブジェクト
(クラス)
x != y を実装する制約付き関数オブジェクト
(クラス)
x < y を実装する制約付き関数オブジェクト
(クラス)
x > y を実装する制約付き関数オブジェクト
(クラス)
x <= y を実装する制約付き関数オブジェクト
(クラス)
x >= y を実装する制約付き関数オブジェクト
(クラス)