std::less on enums

拜拜、爱过 提交于 2019-12-22 06:42:19

问题


Does the standard guarantee that std::less<MyEnumType> will order MyEnumType as if a value of MyEnumType was cast to an appropriately sized integer type?

enum MyEnumType { E1 = 0, E2 = 6, E3 = 3 };

回答1:


Yes, std::less::operator() is defined as (§20.8.5/5):

operator() returns x < y

For using relational operators on enumeration types, the following is stated (§5.9/2):

The usual arithmetic conversions are performed on operands of arithmetic or enumeration type.

For unscoped enumeration types, the usual arithmetic conversions are defined as doing integral promotion. Integral promotion for unscoped enumeration types is defined as (§5/9):

A prvalue of an unscoped enumeration type whose underlying type is not fixed (7.2) can be converted to a prvalue of the first of the following types that can represent all the values of the enumeration (i.e., the values in the range bmin to bmax as described in 7.2): int, unsigned int, long int, unsigned long int, long long int, or unsigned long long int.

An extended integer type will be used if available and required.




回答2:


The type of an enum is defined as some integral type that is large enough to hold all of the values of the enum. The compiler is allowed to decide what the concrete type is (although there is now a way to control this). But the type is definitely some integral type, which means that comparison operators on two values of the same enum type will behave pretty much as you'd expect.



来源:https://stackoverflow.com/questions/13750296/stdless-on-enums

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!