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_ordering和std::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<=>b且a==3 && b==3,那么a<=>b就等于0

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zydgxg.html