Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching on enum class in C++ 0x

Tags:

c++

enums

c++11

Will new "enum class" declarations in C++ 0x allow switching on the new-fangled enums?

I'm asking what the standard says, not about the compiler support.

like image 496
quant_dev Avatar asked Jun 13 '11 06:06

quant_dev


2 Answers

From the n3242 draft:

6.4.2 The switch statement [stmt.switch]

[...]

2 The condition shall be of integral type, enumeration type, or of a class type for which a single non-explicit conversion function to integral or enumeration type exists (12.3).

7.2 Enumeration declarations [dcl.enum]

[...]

enum-key:
    enum
    enum class
    enum struct

This means yes.

like image 145
Luc Danton Avatar answered Oct 13 '22 01:10

Luc Danton


Yes, scoped (enum {class, struct}) enumerations and enumerators will behave exactly the same as unscoped (enum, old style) ones in the context of a switch statement.

n3242 - 6.4.2.2 [stmt.switch]:

The condition shall be of integral type, enumeration type, or of a class type for which a single non-explicit conversion function to integral or enumeration type exists (12.3). If the condition is of class type, the condition is converted by calling that conversion function, and the result of the conversion is used in place of the original condition for the remainder of this section. Integral promotions are performed. Any statement within the switch statement can be labeled with one or more case labels as follows:

case constant-expression :

where the constant-expression shall be an integral constant expression (5.19). The integral constant expression is implicitly converted to the promoted type of the switch condition. No two of the case constants in the same switch shall have the same value after conversion to the promoted type of the switch condition.

In the case of the condition, an enumeration type is listed. This includes both scoped and unscoped enums (see n3242 - 7.2).

As for the case labels, they must be integral constant expressions. Which is a constant expression of integral or enumeration type (see n3242 - 5.19.3).

like image 36
Michael Spencer Avatar answered Oct 13 '22 00:10

Michael Spencer