typestar

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

  1. Level::debug through Level::error must be spelled with their scope — no bare debug.
  2. The switch covers every enumerator, so the compiler can prove nothing is missed.
  3. No implicit conversion: getting the underlying 3 takes an explicit static_cast<int>.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Modern touches, step 24 of 27 in Language basics.

← Previous Next →