Namespaces
Variants

std::compare_three_way

来自 zh.cppreference.net
 
 
 
函数对象
函数调用
(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 :

  • 若从 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 的受约束函数对象
(类)