Strongly Typed enum

C++03 enum Types: Motivation

Why enum? Why isn’t int sufficient?

  • Readability, Semantics

  • switch statements without default label ⟶ -Wswitch warns about missing enumerators

  • Type safety: int cannot be assigned to an enum

    • The other way around is possible

Apart from that, enum is crap!

C++03 enum Types: Problems

  • Enumerators are not in the enum type’s scope

    • Rather, they pollute the surrounding scope

    • ⟶ no two enumerators with the same name

  • Underlying type is not defined ⟶ sizeof depends on compiler

  • Implicit conversion to int


Workarounds possible, although much typing involved!

C++11 enum class

enum class
enum class E1 {
enum class E2 {
E1 e1 = E1::ONE;
E2 e2 = E2::ONE;
int i = e1; // error
    • No conflicts in surrounding scope

    • Body same as before

    • No conversion to int

    • C++03 enum remains unchanged ⟶ code compatibility

    • ⟶ Cool!

C++11 enum class: Underlying Type

Explicit type
#include <cstdint>
#include <cassert>
enum E: uint8_t {
void f() {
  • In C++03 enum and enum class possible

  • Default: int

  • Works with every integer types except wchar_t