Scoped enums in C++
enum class keeps enumerators out of the surrounding scope and off implicit int.
#include <string_view>
enum class Level { debug, info, warning, error };
constexpr std::string_view name_of(Level lvl) {
switch (lvl) {
case Level::debug: return "debug";
case Level::info: return "info";
case Level::warning: return "warning";
case Level::error: return "error";
}
return "unknown";
}
static_assert(name_of(Level::warning) == "warning");
static_assert(static_cast<int>(Level::error) == 3);
How it works
Level::debugthroughLevel::errormust be spelled with their scope — no baredebug.- The
switchcovers every enumerator, so the compiler can prove nothing is missed. - No implicit conversion: getting the underlying
3takes an explicitstatic_cast<int>.
Keywords and builtins used here
Levelcaseclassconstexprenumintname_ofreturnstatic_assertstatic_castswitch
The run, in numbers
- Lines
- 16
- Characters to type
- 414
- Tokens
- 116
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 87 seconds.
Step 3 of 3 in Modern touches, step 24 of 27 in Language basics.