Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::less on enums

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 };
like image 688
Thomas Eding Avatar asked Dec 06 '12 18:12

Thomas Eding


2 Answers

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.

like image 105
Joseph Mansfield Avatar answered Oct 06 '22 19:10

Joseph Mansfield


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.

like image 45
Lily Ballard Avatar answered Oct 06 '22 21:10

Lily Ballard