首页 > 解决方案 > 如何强制 std::weak_ordering

问题描述

在试用新品时领带拦截器三向比较运算符<=>我想知道这样的例子是什么

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但是如何强制编译器这样做呢?

到目前为止,我已经阅读了 strong_ordering 和 weak_ordering的实际含义。

标签: c++c++20spaceship-operatorstrict-weak-ordering

解决方案


...但是如何强制编译器这样做呢?

当你使用autodefaulted 作为返回类型时operator<=>,编译器会选择所有成员的共同比较类别。所以如果你有类似的东西:

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

然后<=>在 type 的两个实例上使用Foo会给你一个weak_ordering,因为这是Weakand的常见比较类别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;
};

这里<=>返回(以避免不得不假设andstd::weak_ordering是什么意思)。<==


或者您可以简单地自己提供。您不必使用auto

struct WeakInt {
    int i;
    friend std::weak_ordering operator<=>(WeakInt, WeakInt) = default;
};

推荐阅读