Skip to content

enum class (C++11)

In a Nutshell

Scoped enumerations that resolve the issues of traditional enum types polluting the global namespace and implicitly converting to integers.

No header required (language keyword)

Core API Cheat Sheet

OperationSignatureDescription
Declarationenum class Name { A, B };Basic scoped enum; underlying type defaults to int
Specify Underlying Typeenum class Name : type { A, B };Fixed underlying type to save memory
Access EnumeratorsName::AMust be accessed via scope operator
Cast to Integerstatic_cast<int>(Name::A)Explicit cast required; no implicit conversion
Opaque Declarationenum class Name : type;Forward declaration; underlying type must be specified
using enumusing enum Name;(C++20) Injects enumerators into the current scope

Minimal Example

cpp
enum class Color : uint8_t { Red, Green, Blue };

auto led = Color::Red;

// led = 0;                 // Error: no implicit conversion
if (led == Color::Green) {  // Type-safe comparison
    // ...
}

int value = static_cast<int>(led); // Explicit cast

Embedded Applicability: High

  • Specifying the underlying type (e.g., uint8_t, uint32_t) allows precise control over memory usage, which is ideal for protocol parsing and register mapping.
  • Zero runtime overhead; fully resolved at compile time.
  • Eliminates naming conflicts, making it suitable for modular development in large embedded projects.
  • Explicit type conversion prevents accidental integer comparisons, enhancing code safety.

Compiler Support

GCCClangMSVC
4.73.12010

See Also


部分内容参考自 cppreference.com,采用 CC-BY-SA 4.0 许可

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05