c++ - 如何强制 std::weak_ordering

标签 c++ c++20 spaceship-operator strict-weak-ordering

在尝试新的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/

相关文章:

ruby - 与 Ruby 的 <=> 运算符混淆

c++ - 无法在 C++ OpenCV HSV 图像分离中分离对象

c++ - 我的二进制搜索程序简单地关闭了

c++ - QtSerialPort:在 Windows 7 上重复读取

c++ - 为什么 std::bit_width 为值 0 返回 0,它不应该返回 1 吗?

c++ - 如何通过创建类型特征来对 NTTP 类进行分类?

c++ - 使用基类的注入(inject)类名进行限定依赖名称查找

c++ - 如何在模板类定义中构造自定义类型

mysql - MySQL 中的这个运算符 <=> 是什么?

ruby - 什么是 Ruby <=>(宇宙飞船)运算符?