Strongly Typed Enums (C++11)

From RAD Studio
Jump to: navigation, search

Go Up to C++11 Features in the Classic Compiler

Attention: This page refers to a C++11 feature in the Classic compiler. The Classic compiler is not recommended: instead it is recommend you use the Clang-enhanced compilers, which support modern C++ including C++11, C++14 and C++17.

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

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:

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:

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:

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:

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
enum class E { a, b };
enum E x1 = E::a; // OK
enum class E x2 = E::a; // illegal

See Also