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 };
Yes, std::less::operator()
is defined as (§20.8.5/5):
operator()
returnsx < 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
, orunsigned long long int
.
An extended integer type will be used if available and required.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With