命名空间
变体
操作

std::compare_three_way

来自 cppreference.cn
< 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 的受限函数对象
(类) [编辑]