前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++20草案中的宇宙飞船运算符(<=>,spaceship operator)

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

作者头像
racaljk
发布2018-10-10 09:46:47
9340
发布2018-10-10 09:46:47
举报
文章被收录于专栏:racaljkracaljk

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的值定义如下:

代码语言:javascript
复制
+--------------------------------------------------------------------+
|                  |          Numeric  values          | Non-numeric |
|     Category     +-----------------------------------+             |
|                  | -1   | 0          | +1            |   values    |
+------------------+------+------------+---------------+-------------+
| strong_ordering  | less | equal      | greater       |             |
| weak_ordering    | less | equivalent | greater       |             |
| partial_ordering | less | equivalent | greater       | unordered   |
| strong_equality  |      | equal      | nonequal      |             |
| weak_equality    |      | equivalent | nonequivalent |             |
+------------------+------+------------+---------------+-------------+

也就是说,返回的是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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • C++20草案中的宇宙飞船运算符(<=>,spaceship operator)
  • 更多
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档