1

考虑以下代码:

#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

4

1 回答 1

3

您需要提供一个==以及<=>. 不仅std::ranges::less需要,所以也需要。除非ed,否则不会合成.std::totally_orderedstd::strict_weak_order==default<=>==

#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;
};

auto operator <=>(const A &a1, const A &a2) { return a1.a <=> a2.a; }
auto operator ==(const A &a1, const A &a2) { return a1.a == a2.a; }

int main()
{
   assert(A {} < A{}); // Comparison exists
   std::vector<A> c;
   assert(std::ranges::is_sorted(c)); // Comparison exists
}
于 2021-03-09T10:55:47.327 回答