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
};
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...
}
}
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
}
}
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;
}
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)
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]
Just like
using namespace std;
orusing std::cout;
, you should you useusing 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?
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.
I understand your pain...