当前位置:   article > 正文

C++20草案中的宇宙飞船运算符(<=>,spaceship operator)

宇宙飞船运算符

C++20草案中的宇宙飞船运算符(<=>,spaceship operator)

Herb Sutter提议的新三路运算符<=>已经被合入C++20草案中

宇宙飞船运算符(hh)形式如lhs<=>rhs
比如a与b是整型,那么a<=>b返回std::strong_ordering类型的纯右值(prvalue,不能取地址那种):

  • 如果a<b,(a<=>b)返回std::strong_ordering::less
  • 如果a>b,(a<=>b)返回std::strong_ordering::greater
  • 如果a与b全等/相等,(a<=>b)返回std::strong_ordering::equal

如果a b是浮点值,就返回的是std::partial_ordering::less/greater/equivalent或者std::partial_ordering::unordered(如果ab中有一个NaN)

标准还有更多规定,比如a与b是指针,a与b是枚举等,详细内容请参见更多

最后,std::strong_orderingstd::partial_ordering的值定义如下:

  1. +--------------------------------------------------------------------+
  2. | | Numeric values | Non-numeric |
  3. | Category +-----------------------------------+ |
  4. | | -1 | 0 | +1 | values |
  5. +------------------+------+------------+---------------+-------------+
  6. | strong_ordering | less | equal | greater | |
  7. | weak_ordering | less | equivalent | greater | |
  8. | partial_ordering | less | equivalent | greater | unordered |
  9. | strong_equality | | equal | nonequal | |
  10. | weak_equality | | equivalent | nonequivalent | |
  11. +------------------+------+------------+---------------+-------------+

也就是说,返回的是0/1/-1,还记得strcmp(stra,strb)吧,<=>设计理念之一正是基于这种函数,如果a<=>ba==3 && b==3,那么a<=>b就等于0

更多

http://open-std.org/JTC1/SC22/WG21/docs/papers/2017/p0515r0.pdf
https://en.cppreference.com/w/cpp/language/operator_comparison

转载于:https://www.cnblogs.com/ysherlock/p/9629599.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/664156
推荐阅读
相关标签
  

闽ICP备14008679号