gpt4 book ai didi

c++ - 为什么在 C++20 中删除了许多标准库类型的运算符!=?

转载 作者:行者123 更新时间:2023-12-02 02:43:03 24 4
gpt4 key购买 nike

根据cppreferencestd::type_info::operator!= 在 C++20 中被删除,但是 std::type_info::operator== 显然仍然存在。

背后的原因是什么?我可能同意比较不平等是没有意义的,但是比较平等也同样没有意义,不是吗?

类似地,许多其他标准库类型的operator!=,包括诸如 std::unordered_map::operator!= 之类的容器和 std::unordered_set::operator!=根据 cppreference 将在 C++20 中删除。

if(id1 != id2)) 相比,编写 if(!(id1 == id2)) 并不会让任何代码变得更清晰,相反,恰恰相反...

最佳答案

在 C++20 中,关系运算符的工作方式发生了变化,特别是随着宇宙飞船 <=> 的引入。运算符(operator)。特别是,如果您只提供operator== ,然后a != b被重写为!(a == b)

来自[over.match.oper]/3.4 :

The rewritten candidate set is determined as follows:

  • For the relational ([expr.rel]) operators, the rewritten candidates include all non-rewritten candidates for the expression x <=> y.
  • For the relational ([expr.rel]) and three-way comparison ([expr.spaceship]) operators, the rewritten candidates also include a synthesized candidate, with the order of the two parameters reversed, for each non-rewritten candidate for the expression y <=> x.
  • For the != operator ([expr.eq]), the rewritten candidates include all non-rewritten candidates for the expression x == y.
  • For the equality operators, the rewritten candidates also include a synthesized candidate, with the order of the two parameters reversed, for each non-rewritten candidate for the expression y == x.
  • For all other operators, the rewritten candidate set is empty.

[over.match.oper]/9 :

If a rewritten operator== candidate is selected by overload resolution for an operator @, its return type shall be cv bool, and x @ y is interpreted as:

  • if @ is != and the selected candidate is a synthesized candidate with reversed order of parameters, !(y == x),
  • otherwise, if @ is !=, !(x == y),
  • otherwise (when @ is ==), y == x,

in each case using the selected rewritten operator== candidate.

因此,operator!= 的显式重载不再需要了。删除运算符并没有改变比较语义。

所有容器都有其operator!=据我所知,已删除(例如 the vector synopsis )。唯一的异常(exception)是容器适配器 std::queuestd::stack :我的猜测是,它是为了在与第三方容器一起使用时保持向后兼容性,以防相等运算符不对称。

关于c++ - 为什么在 C++20 中删除了许多标准库类型的运算符!=?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58319928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com