c++ - 如何强制 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的实际含义。
解决方案
...但是如何强制编译器这样做呢?
当你使用auto
defaulted 作为返回类型时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
,因为这是Weak
and的常见比较类别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;
};
推荐阅读
- google-apps-script - 当数据仅在 A 列中重复时删除 Google 表格中的行
- html - 垂直滚动条卡在页面上
- powerbi - Powerbi 从多个表创建度量
- pandas - Pandas:打印到 csv 还会创建一个带有行索引的未标记列
- android - Android,我是否使用 ViewModel 执行插入或更新?
- java - 将 BitSet 转换为 Byte[]
- python - 在 Django 中格式化 DateTimeField
- avro - Avro 模式:添加一个具有默认值的新字段 - 直接默认值或带有 null 的联合?
- javascript - 动态 Javascript 表单输入未发布
- spring - JHipster-registry 空白页