在尝试新的Tie-Interceptor 三向比较运算符时 <=>
我想知道这样的例子是什么
struct Foo {
/*
....
*/
auto operator<=>(const Foo &rhs) const = default;
};
会导致编译器错误
Foo Bar1;
Foo Bar2;
std::strong_ordering(Bar1 <=> Bar2);
但不是
Foo Bar1;
Foo Bar2;
std::weak_ordering(Bar1 <=> Bar2);
Foo
的例子是什么? ?换句话说 Foo
会怎样?不是暗示可替代性?
我知道我可以编写自己的运算符实现,它返回 std::weak_ordering ... less/greater/equivalent
但是如何强制编译器这样做呢?
我读过 Practical meaning of strong_ordering and weak_ordering到目前为止。
最佳答案
... but how to force the compiler to do so?
当您使用 auto
时作为默认 operator<=>
的返回类型,编译器将选择所有成员的公共(public)比较类别。所以如果你有这样的东西:
// any type that is weakly ordered
struct Weak {
bool operator==(Weak const&) const;
std::weak_ordering operator<=>(Weak const&) const;
};
struct Foo {
Weak w;
int i;
auto operator<=>(Foo const&) const = default;
};
然后使用 <=>
在 Foo
类型的两个实例上会给你一个weak_ordering
,因为这是 Weak
的常见比较类别和 int
.
与给定的方式相同:
struct Bar {
float f;
auto operator<=>(Bar const&) const = default;
};
Bar::operator<=>
给你一个 std::partial_ordering
.
没有核心语言类型可以给你 std::weak_ordering
,但是有一些库类型可能:
// some typical C++17 comparable type
struct Widget {
bool operator==(Widget const&) const;
bool operator<(Widget const&) const;
};
struct LotsOfWidgets {
std::vector<Widget> widgets;
auto operator<=>(LotsOfWidgets const&) const = default;
};
<=>
这里返回 std::weak_ordering
(以避免必须假设 <
和 ==
是什么意思)。
或者您可以自己提供。您不必使用 auto
:
struct WeakInt {
int i;
friend std::weak_ordering operator<=>(WeakInt, WeakInt) = default;
};
关于c++ - 如何强制 std::weak_ordering,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61411276/