std::compare_weak_order_fallback
来自cppreference.com
| 在标头 <compare> 定义
|
||
| |
(C++20 起) | |
| 调用签名 |
||
| |
(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和t < 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
- 但
t和u都只会求值一次。
所有其他情况下 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
|
加强了约束 |
参阅
(C++20) |
进行三路比较并产生 std::weak_ordering 类型的结果 (定制点对象) |