RAD Studio
ContentsIndex
PreviousUpNext
Strongly Typed Enums (C++0x)

C++Builder 2009 introduces scoped enums. In addition, existing enums are extended with underlying type and explicit scoping. This feature is one of the C++0x features added to C++Builder 2009.  

Scoped enums are generally characterized as follows:

  • Enumerators are in the scope of their enum.
  • Enumerators and enums do not implicitly convert to int (as do "plain" enumerators and enums).
  • Enums and their enumerators can have a defined underlying type.

You declare a scoped enum by specifying enum class or enum struct. For example:

enum class A {A1, A2, A3 = 50, A4 /* = 51 */}; 

With scoped enums, there is no longer any implicit conversion to or from an integer.

For scoped enums, the underlying type is well specified (the default is int). You can specify the underlying type of the enumeration and all the enumerators by writing : type after the enumeration name (you can specify any integral type except wchar_t). The following example declares an enum of underlying type unsigned long:

enum class A : unsigned long {A1 = 1, A2 = 2, Abig = 0xFFFFFFFOU }; 

A scoped enum introduces its own scope. The names of enumerators are in the enum's scope, and are not injected into the enclosing scope. For instance:

enum class A { A1, A2, A3 = 100, A4 /* = 101 */ };
A a1 = A1;  // error
A a2 = A::A2;   // OK-scope specified

In addition, existing enums are being extended as follows:

  • You can now specify the underlying type of any enum, just as with scoped enums (by adding : type to the declaration).
  • Existing enums now introduce their own scopes, just as with scoped enums. The names of enumerators are defined in the enum's scope and are also injected into the enclosing scope.
For instance:

enum B { B1, B2, B3 = 100, B4 /* = 101 */ };
B b1 = B1;  // ok
B b2 = B::B2;   // ok 

The following examples demonstrate the following two things:

  • The method for calling scoped enumerators
  • The fact that enum class (and enum struct) cannot be specified with elaborated-type-specifiers

enum class E { a, b }; 
enum E x1 = E::a; // OK 
enum class E x2 = E::a; // illegal  
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!