为什么从 C++ 20 的标准库容器中删除了比较运算符?
Why have comparison operators been removed from standard library containers in C++ 20?
我正在浏览 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 会开始在旧代码上出错吗?
如果您继续浏览参考站点,您可能会看到关于 default comparisons 的部分,它简单地指出:
In brief, a class that defines operator<=>
automatically gets compiler-generated operators <
, <=
, >
, and >=
.
因此,如果 "spaceship" 运算符存在于 class,编译器将使用 <=>
运算符的结果自动生成剩余的比较运算符。
请注意 ==
运算符 不是 生成的(即使它应该是可能的),但 std::vector
保持 [=18= 的重载].
至于:
will C++ 20 start giving errors on older codes ?
不,不会。
当您使用 C++20 编译器构建时,与其一起使用的标准库应该也 为 C++20 制作,从而实现 <=>
运算符,然后将按上述说明使用。
但是,如果您使用 C++20 编译器构建较旧的标准库,则该较旧的标准库仍会实现较旧的比较运算符。
我正在浏览 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 会开始在旧代码上出错吗?
如果您继续浏览参考站点,您可能会看到关于 default comparisons 的部分,它简单地指出:
In brief, a class that defines
operator<=>
automatically gets compiler-generated operators<
,<=
,>
, and>=
.
因此,如果 "spaceship" 运算符存在于 class,编译器将使用 <=>
运算符的结果自动生成剩余的比较运算符。
请注意 ==
运算符 不是 生成的(即使它应该是可能的),但 std::vector
保持 [=18= 的重载].
至于:
will C++ 20 start giving errors on older codes ?
不,不会。
当您使用 C++20 编译器构建时,与其一起使用的标准库应该也 为 C++20 制作,从而实现 <=>
运算符,然后将按上述说明使用。
但是,如果您使用 C++20 编译器构建较旧的标准库,则该较旧的标准库仍会实现较旧的比较运算符。