考虑以下代码:
#include <vector>
#include <algorithm>
#include <ranges>
#include <cassert>
// The type is defined in legacy code and we can not change it
struct A
{
int a;
};
bool operator <(const A &a1, const A &a2)
{
return a1.a < a2.a;
}
int main()
{
assert(A {} < A{}); // OK
std::vector<A> c;
assert(std::ranges::is_sorted(c)); // compilation error
}
可以通过在 A 中添加“spaceship”比较运算符来修复代码:
auto operator<=>(const A &) const = default;
但是,在类之外定义它适用于第一个assert
,而不是第二个:
auto operator <=>(const A &a1, const A &a2) { return a1.a <=> a2.a; }
ranges::less
不修改是否可以满足要求A
?