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

+--------------------------------------------------------------------+
|                  |          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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章