DEV Community

Pierre Gradot
Pierre Gradot

Posted on • Edited on

Let's try C++20 | using enum

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 😀

Top comments (4)

Collapse
 
maresia profile image
Maresia

With auto complete features like using enum seem useless and problematic. I prefer to use the full name to avoid the name conflict that can occur as the code grows.
[from google translate]

Collapse
 
pgradot profile image
Pierre Gradot • Edited

Just like using namespace std; or using std::cout;, you should you use using enum EnumWithALongName; in a (very) limited scope to avoid conflicts.

From my experience, if everything function / type / constant is in a namespace, has a descriptive name, and you avoid wide scopes, you will almost run into troubles.

And I assume the C++ committee as the same point view since they added using enum xxx to C++20 ;)

Have you experienced some issues?

Collapse
 
maresia profile image
Maresia • Edited

Yes, it has occurred to me to use one function by mistake, imagining it to be another. The result was a code that behaved very strangely and I only noticed that it used the wrong function much later after spending a long time fighting with gdb. Since then I use this extensively and avoid using.

Thread Thread
 
pgradot profile image
Pierre Gradot

I understand your pain...