Namespaces
Variants

std:: compare_weak_order_fallback

From cppreference.net
Utilities library
定义于头文件 <compare>
inline namespace /* 未指定 */ {

inline constexpr /* 未指定 */
compare_weak_order_fallback = /* 未指定 */ ;

}
(C++20 起)
调用签名
template < class T, class U >

requires /* 见下文 */
constexpr std:: weak_ordering

compare_weak_order_fallback ( T && t, U && u ) noexcept ( /* 见下文 */ ) ;
(C++20 起)

子表达式 t u 进行三路比较,并生成 std::weak_ordering 类型的结果,即使运算符 <=> 不可用。

如果 std:: decay_t < T > std:: decay_t < U > 是相同类型, std :: compare_weak_order_fallback ( t, u ) 表达式等价性 上等同于:

  • std:: weak_order ( t, u ) ,如果它是合法表达式;否则,
  • t == u ? std :: weak_ordering :: equivalent :
    t < u ? std :: weak_ordering :: less :
    std :: weak_ordering :: greater
    ,如果表达式 t == u t < u 均为合法表达式,且 decltype ( t == u ) decltype ( t < u ) 均满足 boolean-testable 概念,但 t u 仅会被求值一次。

在所有其他情况下, std :: compare_weak_order_fallback ( t, u ) 的格式不正确,当其出现在模板实例化的直接上下文中时,可能导致 替换失败

目录

定制点对象

名称 std::compare_weak_order_fallback 表示一个 定制点对象 ,这是一个字面量 semiregular 类类型的常量 函数对象 。详细信息请参阅 定制点对象

示例

#include <compare>
#include <iostream>
// 不支持 <=>
struct Rational_1
{
    int num;
    int den; // > 0
};
inline constexpr bool operator<(Rational_1 lhs, Rational_1 rhs)
{
    return lhs.num * rhs.den < rhs.num * lhs.den;
}
inline constexpr bool operator==(Rational_1 lhs, Rational_1 rhs)
{
    return lhs.num * rhs.den == rhs.num * lhs.den;
}
// 支持 <=>
struct Rational_2
{
    int num;
    int den; // > 0
};
inline constexpr std::weak_ordering operator<=>(Rational_2 lhs, Rational_2 rhs)
{
    return lhs.num * rhs.den <=> rhs.num * lhs.den;
}
inline constexpr bool operator==(Rational_2 lhs, Rational_2 rhs)
{
    return lhs <=> rhs == 0;
}
void print(int id, std::weak_ordering value)
{
    std::cout << id << ") ";
    if (value == 0)
        std::cout << "equal\n";
    else if (value < 0)
        std::cout << "less\n";
    else
        std::cout << "greater\n";
}
int main()
{
    Rational_1 a{1, 2}, b{3, 4};
//  print(0, a <=> b); // 无法工作
    print(1, std::compare_weak_order_fallback(a, b)); // 正常工作,回退到 < 和 ==
    Rational_2 c{6, 5}, d{8, 7};
    print(2, c <=> d); // 正常工作
    print(3, std::compare_weak_order_fallback(c, d)); // 正常工作
    Rational_2 e{2, 3}, f{4, 6};
    print(4, e <=> f); // 正常工作
    print(5, std::compare_weak_order_fallback(e, f)); // 正常工作
}

输出:

1) less
2) greater
3) greater
4) equal
5) equal

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

缺陷报告 适用范围 发布时行为 正确行为
LWG 2114
( P2167R3 )
C++20 后备机制仅要求
返回类型可转换为 bool
约束条件已加强

参见

(C++20)
执行三路比较并生成 std::weak_ordering 类型的结果
(定制点对象)