为什么在C ++ 20中不推荐使用std :: rel_ops :: operators?
根据 cppreference.com , std :: rel_ops :: operator!=,>,< =,> =
在C ++ 20中将不推荐使用。
According to cppreference.com, std::rel_ops::operator!=,>,<=,>=
will be deprecated in C++20.
背后的原理是什么?
在C ++ 20中,您会得到三向比较(运算符< =>
),它会自动生成 默认比较(如果提供):
In C++20, you get three-way comparison (operator <=>
), which automatically "generates" default comparisons if provided:
struct A {
// You only need to implement a single operator.
std::strong_ordering operator<=>(const A&) const;
};
// Compiler generates 4 relational operators (you need to default the
// three-way comparison operator to get == and !=).
A to1, to2;
if (to1 > to2) { /* ... */ } // ok
if (to1 <= to2) { /* ... */ } // ok, single call to <=>
与 std :: rel_ops相比,三元比较有多个优点
,这可能是为什么不推荐使用 std :: rel_ops
运算符的原因。在我的头上:
There are multiple advantages of the three-way comparison over std::rel_ops
, which is probably why std::rel_ops
operators are deprecated. On top of my head:
-
它更加通用,因为取决于
的返回类型运算符< =>
(std :: strong_ordering
,std :: weak_ordering
,。 ..),仅生成相关的运算符。请参见< compare>
标头以获取更多信息。
It is more versatile, since, depending on the return type of
operator<=>
(std::strong_ordering
,std::weak_ordering
, ...), only relevant operators are generated. See the<compare>
header for more information.
使用命名空间std :: rel_ops进行不会带来大量模板操作符重载
。
You do not bring a bunch of templated operator overloads by doing using namespace std::rel_ops
.
您可以要求编译器通过默认方式为您生成三元运算符(自动运算符< =>(A const&)=默认值
)—基本上,这将对基类和非静态数据成员进行字典比较,并且如果返回类型为 auto
,则会推断出正确的排序类型。
You can ask the compiler to generate the three-way operator for you by defaulting it (auto operator<=>(A const&) = default
) — This will basically generate a lexicographic comparison of base classes and non-static data members, plus it will deduce the right type of ordering if the return type is auto
.