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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM