Let's try C++20 | using enum

Pierre Gradot - Dec 22 '20 - - Dev Community

Proposal P1099R5 by Gašper Ažman and Jonathan Müller adds the possibility to write using enum my_enum; so that the names inside the enumeration my_enum can be used directly, with being preceded by my_enum::.

Let's consider an enumeration like this:

enum class EnumWithALongName {
    FirstValue,
    SecondValue,
    YetAnotherValue
};
Enter fullscreen mode Exit fullscreen mode

Until C++17, you had to write their fully qualified names to use the enumerators. Sometimes, it would make code quite verbose:

void process(EnumWithALongName value) {
    switch(value) {
        case EnumWithALongName:::FirstValue:
            // stuff
        case EnumWithALongName::SecondValue:
            // more stuff
        case EnumWithALongName::YetAnotherValue:
            // OK, I got it, we are dealing with EnumWithALongName...
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks to C++20, we can now write:

void process(EnumWithALongName value) {
    switch(value) {
        using enum EnumWithALongName; // this is new \o/

        case FirstValue:
            // stuff
        case SecondValue:
            // more stuff
        case YetAnotherValue:
            // code is more readable like this
    }
}
Enter fullscreen mode Exit fullscreen mode

It is also possible to bring up only some particular enumerators from an enumeration:

int main() {
    using EnumWithALongName::FirstValue, EnumWithALongName::SecondValue;
    auto value = FirstValue;
    return value != SecondValue;
}
Enter fullscreen mode Exit fullscreen mode

In my opinion, the last reason to use unscoped enums was the possibility to use them without being preceded by the name of the enumeration. This reason has now disappeared 😀

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player