RAD Studio |  |

Strongly Typed Enums (C++0x)
Declaration | No Implicit Type Conversion | Underlying Type | Scoping | Changes to Existing Enums | Examples | See Also
Collapse All

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.

Declaration

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

Copy Code

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

No Implicit Type Conversion

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

Underlying Type

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:

Copy Code

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

Scoping

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:

Copy Code

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

Changes to Existing Enums

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:
Copy Code

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

Examples

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

Copy Code

    enum class E { a, b };
    enum E x1 = E::a; // OK
    enum class E x2 = E::a; // illegal

See Also

C++0x Features (C++Builder 2009)

Strongly Typed Enums (Revision 3)

Forward Declaration of Enumerations

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!