C++20: enum class and using Declarations

C++11 has given use strongly-typed enumeration types which are recommended to be used over the old style enumeration types. The problem with the latter is that the enumerators of such old-style enumeration types are automatically exported into the enclosing scope. This can cause naming collisions with names already defined in the enclosing scope. This is also the reason why enumerators of such types are often prefixed with some label to try to make sure they are unique. For example:

enum Color { ColorRed, ColorGreen, ColorBlue };

The strongly-typed enumeration types from C++11 do not automatically export their enumerators to the enclosing scope.

Let’s look at an example. The following defines and uses a strongly-type enumeration type called Color:

enum class Color { Red, Green, Blue };
Color someColor = Color::Green;

To use the enumerators of the Color enumeration type, you need to fully qualify them with Color::. This can become a bit cumbersome if you, for example, need to have a switch statement on the different enumerators:

switch (someColor) {
    case Color::Red:
        // ...
        break;
    case Color::Green:
        // ...
        break;
    case Color::Blue:
        // ...
        break;
}

Since C++20, you can use a using declaration to avoid having to fully qualify all the different enumerators in the switch cases:

switch (someColor) {
    using enum Color;

    case Red:
        // ...
        break;
    case Green:
        // ...
        break;
    case Blue:
        // ...
        break;
}

Of course, it is recommended to have the scope of the using declaration as small as possible, otherwise you again introduce the risk of having naming collisions. That’s why the using declaration in the earlier example is inside the scope of the switch statement.

My book, Professional C++, 5th Edition, explains all new C++20 features, and much more.

Share

2 Comments so far »

  1. Harry said,

    Wrote on March 3, 2024 @ 10:11 am

    From which version of g++ is this supported?

  2. Marc Gregoire said,

    Wrote on March 3, 2024 @ 7:30 pm

    cppreference.com has a nice list of features including from which compiler version they are supported
    https://en.cppreference.com/w/cpp/compiler_support

Comment RSS · TrackBack URI

Leave a Comment

Name: (Required)

E-mail: (Required)

Website:

Comment: