C++0x: Strongly typed enumerations

From Dwarf Wiki
Jump to: navigation, search

For detail description of the feature, please refer to:




Current C++ enums are not type-safe. This is because an enumeration type is promoted to an integer by integral promotion.

enum Color { ClrRed, ClrOrange, ClrYellow, ClrGreen, ClrBlue, ClrViolet };
enum Alert { CndGreen, CndYellow, CndRed };
Color c = ClrRed;
Alert a = CndGreen;

bool armWeapons = ( a >= ClrYellow );     // Compiles okay, but not desirable

A new strongly-type enum is therefore created: enum class. There is no implicit conversion between enum class and int. And the underlying type is always well-specified.

enum class A { A1=1 };                 // underlying type is int by default
enum class B: unsigned long { B1=1 };  // underlying type is unsigned long

enum class introduces its own scope. The names of enumerators are in the enum’s scope, and are not injected into the enclosing scope.

enum class E { E1, E2, E3 = 100, E4 /* = 101 */ };
E e1 = E1;      // error
E e2 = E::E2;   // ok

Proposed change to DWARF

New DWARF attribute

DW_AT_enum_class 0x70 flag A strongly typed enumeration type

5.8 Enumeration Type Entries

If an enumeration type has type-safe semantics such that:

  • enumerators are contained in the scope of the enumeration type
  • enumerators do not implicitly convert to or from another type

then the enumeration type may have a DW_AT_enum_class attribute specifying those semantics. The value of this attribute is a flag.

In C++0x, a type declared using enum class is a 'strongly typed enumeration type', and would be represented with this attribute.


enum class E { E1, E2=100 };
E e1;

11$:  DW_TAG_enumeration_type
          DW_AT_type(reference to base type "int")
12$:      DW_TAG_enumerator
13$:      DW_TAG_enumerator
14$:  DW_TAG_variable
          DW_AT_type(reference to 11$)

Change History

May 7, 2009.

  • Remove DW_TAG_strong_enumueration_type, in favor of DW_AT_enum_class
  • Update example to use new attribute.
  • Update 5.8 to describe strongly typed enumeration with DW_AT_enum_class

June 3, 2009.

  • Reword 5.8 to remove C++0x from normative text

June 8, 2009.

  • John Bishop suggests alternate wording for 5.8. (With normative text in front)

July 2, 2009.

  • David Gross suggests replacing "enumeration elements" with "enumerators"
  • David Gross pointed out correct indentation for "DW_TAG_enumerator".