Why is this an issue?
C++20 extends the using
declaration to class enum
. using enum
introduces all the enum
constants
into the current scope.
enum class rgbaColorChannel { red, green, blue, alpha };
std::string_view toString(rgbaColorChannel channel) {
switch (channel) {
using enum rgbaColorChannel;
case red: return "red";
case green: return "green";
case blue: return "blue";
case alpha: return "alpha";
}
}
As with other using
declarations, using enum
improves readability when used in small scopes yet might generate confusion
in large scopes.
The switch
statement, as in the example above, when applied to a class enum
value, is a natural scope for using
enum
.
This rule reports scopes that use a particular class enum
extensively and could benefit from using enum
declaration. For
example, it reports most switch
statements applied to an enum
value.
Noncompliant code example
enum class DayOfTheWeek { mon, tue, wed, thu, fri, sat, sun };
bool isWorkDay(DayOfTheWeek day) {
switch(day) { // Noncompliant: case statements are too verbose
case DayOfTheWeek::mon: return true;
case DayOfTheWeek::tue: return true;
case DayOfTheWeek::wed: return true;
case DayOfTheWeek::thu: return true;
case DayOfTheWeek::fri: return true;
case DayOfTheWeek::sat: return false;
case DayOfTheWeek::sun: return false;
}
}
Compliant solution
enum class DayOfTheWeek { mon, tue, wed, thu, fri, sat, sun };
bool isWorkDay(DayOfTheWeek day) {
switch(day) {
using enum DayOfTheWeek;
case mon: return true;
case tue: return true;
case wed: return true;
case thu: return true;
case fri: return true;
case sat: return false;
case sun: return false;
}
}
Exceptions
The rule will not apply if adding the using enum
clause would create a name collision or reduce readability by shadowing a name.