Namespaces
Variants

std::compare_weak_order_fallback

来自 zh.cppreference.net
 
 
 
定义于头文件 <compare>
inline namespace /* unspecified */ {
    inline constexpr /* unspecified */
        compare_weak_order_fallback = /* unspecified */;
}
(C++20 起)
调用签名
template< class T, class U >
    requires /* see below */
constexpr std::weak_ordering
    compare_weak_order_fallback( T&& t, U&& u ) noexcept(/* see below */);
(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 类型的结果
(定制点对象)