为什么在C ++ 20中从标准库容器中删除了比较运算符? [英] Why have comparison operators been removed from standard library containers in C++ 20?
问题描述
我正在浏览 cppreference ,并看到了 vector
的比较操作已在C ++ 20中删除,并且引入了飞船运算符(< =>
).对于许多其他标准库容器,例如 set
和 map
.
I was browsing cppreference and saw that vector
's comparison operations have been removed in C++20, and the spaceship operator (<=>
) has been introduced. The same thing can be seen for many other standard library containers like set
and map
.
如何在新标准中进行比较?另外,C ++ 20是否会开始在较旧的代码上出现错误?
How do I do the comparisons in the new standard? Also, will C++20 start giving errors on older code?
推荐答案
If you continue to browse on the reference site a little, you might come to the section on default comparisons, which simply states that:
简而言之,定义
operator< =>
的类会自动获取编译器生成的运算符<
,< =
,>
和> =
.
In brief, a class that defines
operator<=>
automatically gets compiler-generated operators<
,<=
,>
, and>=
.
因此,如果某个类存在"spaceship"运算符,则编译器将使用< =>
运算符的结果自动生成其余的比较运算符.
So, if the "spaceship" operator exists for a class, the compiler will auto-generate the remaining comparison operators using the result of the <=>
operator.
请注意, ==
运算符不是 生成的(即使可能),但是 std :: vector
会保持重载的 operator ==
.
Note that the ==
operator is not generated (even though it should be possible), but std::vector
keeps an overload of operator==
.
至:
C ++ 20将开始在较旧的代码上出现错误吗?
will C++ 20 start giving errors on older codes ?
不,不会.
当您使用C ++ 20编译器进行编译时,与其一起使用的标准库也应该针对C ++ 20制作,从而实现< =>
运算符,该运算符将按上述说明使用.
When you build with a C++20 compiler, the standard library used with it should also be made for C++20 and thus implement the <=>
operator, which will then be used as explained above.
但是,如果您使用C ++ 20编译器来构建较旧的标准库,则该较旧的标准库仍将实现较旧的比较运算符.
However, if you use a C++20 compiler to build with an older standard library, that older standard library will still have the older comparison operators implemented.
这篇关于为什么在C ++ 20中从标准库容器中删除了比较运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!