std::compare_weak_order_fallback

来自cppreference.com
< cpp‎ | utility
 
 
 
在标头 <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 起)

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

如果 std::decay_t<T>std::decay_t<U> ���相同的类型,那么 std::compare_weak_order_fallback(t, u) 表达式等价于:

  • std::weak_order(t, u),如果它良构;
  • 否则,如果表达式 t == ut < u 都良构,并且 decltype(t == u)decltype(t < u) 都实现 boolean-testable,则是 t == u ? std::weak_ordering::equivalent :
    t < u  ? std::weak_ordering::less :
             std::weak_ordering::greater
tu 都只会求值一次。

所有其他情况下 std::compare_weak_order_fallback(t, u) 都非良构,这能在出现于模板实例��的立即语境时导致代换失败

目录

定制点对象

名字 std::compare_weak_order_fallback 代表一个定制点对象,它是某个字面 semiregular 类类型的 const 函数对象。 细节参见定制点对象 (CustomizationPointObject)

[编辑] 示例

#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;
}
 
void print(int id, std::weak_ordering value)
{
    std::cout << id << ") ";
    if (value == 0)
        std::cout << "等于\n";
    else if (value < 0)
        std::cout << "小于\n";
    else
        std::cout << "大于\n";
}
 
int main()
{
    Rational_1 a{1, 2}, b{3, 4};
//  print(1, a <=> b); // 不起效
    print(2, std::compare_weak_order_fallback(a, b)); // 起效,默认到 < 和 ==
 
    Rational_2 c{6, 5}, d{8, 7};
    print(3, c <=> d); // 起效
    print(4, std::compare_weak_order_fallback(c, d)); // 起效
 
    Rational_2 e{2, 3}, f{4, 6};
    print(5, e <=> f); // 起效
    print(6, std::compare_weak_order_fallback(e, f)); // 起效
}

输出:

2) 小于
3) 大于
4) 大于
5) 等于
6) 等于

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
LWG 2114
(P2167R3)
C++20 后备机制仅要求返回类型可隐式转换到 bool 加强了约束

[编辑] 参阅

进行三路比较并产生 std::weak_ordering 类型的结果
(定制点对象) [编辑]