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 未指定

成员函数

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

  • 若从 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++ 标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 3530 C++20 比较指针时放宽了语法检查 仅放宽语义要求

参见

实现 x == y 的受约束函数对象
(类)
实现 x ! = y 的受约束函数对象
(类)
实现 x < y 的受约束函数对象
(类)
实现 x > y 的受约束函数对象
(类)
实现 x <= y 的受约束函数对象
(类)
实现 x >= y 的受约束函数对象
(类)