C++0x: Strongly typed enumerations

From wiki.dwarfstd.org
Revision as of 12:01, 16 January 2009 by >Kendrick.wong (New page: For detail description of the feature, please refer to: http://en.wikipedia.org/wiki/C%2B%2B0x#Strongly_typed_enumerations http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2347.p...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

For detail description of the feature, please refer to:

http://en.wikipedia.org/wiki/C%2B%2B0x#Strongly_typed_enumerations

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2347.pdf


Overview

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

none.

DWARF does not differentiate between the existing enum and the new enum class type. Given a program:

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

This implies a debugger will not enforce the strong type checking:

e1 = E1;     // not okay during compilation, but debugger will accept this expression.
e1 = E::E1;  // Debugger should accept this expression.

This should be okay since debuggers are meant to allow the breaking of language rules.

Example

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

<1><  xxx>      DW_TAG_base_type
                DW_AT_name                  int
                DW_AT_encoding              DW_ATE_signed
                DW_AT_byte_size             4
<1><  yyy>      DW_TAG_enumeration_type
                DW_AT_name                  E
                DW_AT_type                  <xxx>    // int
<2><  ###>      DW_TAG_enumerator
                DW_AT_name                  E1
                DW_AT_const_value           0
<2><  ###>      DW_TAG_enumerator
                DW_AT_name                  E2
                DW_AT_const_value           100
<1><  ###>      DW_TAG_variable
                DW_AT_name                  e1
                DW_AT_type                  <yyy>    // enum E