In this article, we are going to learn about the C++ 20 feature of using enums for scoped or strongly typed enums. This feature allows programmers to short hand the syntax for the code using the enums.
In C++ 20 , we got this new improvement for the enums that we can use the using keyword with enums in a given scope. This will help programmers to write the enums values in a shorter syntax, instead of writing the full enum syntax with scope resolution
operator ::.
Let us see this with the help of below example.
Before C++ 20 improvements:
Bring an enum’s members into scope to improve readability.
enum class Number { One, Two, Three, Four };
int string_to_int(Number Num) {
switch (Num) {
case Number::One: return 1;
case Number::Two: return 2;
case Number::Three: return 3;
case Number::Four: return 4;
}
}
After C++ 20 improvements:
enum class Number { One, Two, Three, Four };
int string_to_int(Number Num) {
switch (Num) {
using enum Number;
case Number::One: return 1;
case Number::Two: return 2;
case Number::Three: return 3;
case Number::Four: return 4;
}
}
An example with Structures:
enum class Number { One, Two, Three, Four };
struct PrimeNumbers {
using enum Number;
};
int main()
{
PrimeNumbers No;
No.One;
No::One;
}
An example with Classes:
class PrimeNumbers {
enum class Number {
One,
Two,
Three,
Four
};
using enum Number;
};
int main()
{
PrimeNumbers::Number No = PrimeNumbers::One;
}
Another example:
enum class Number { One, Two, Three, Four };
int main() {
using Number::One, Number::Three;
auto value = One;
return value != Three;
}