Strongly Typed enum#
C++03 enum Types: Motivation#
Why enum? Why isn’t int sufficient?
Readability, Semantics
switchstatements withoutdefaultlabel ⟶-Wswitchwarns about missing enumeratorsType safety:
intcannot be assigned to anenumThe other way around is possible
Apart from that, enum is crap!
C++03 enum Types: Problems#
Enumerators are not in the
enumtype’s scopeRather, they pollute the surrounding scope
⟶ no two enumerators with the same name
Underlying type is not defined ⟶
sizeofdepends on compilerImplicit conversion to
int
Attention
Workarounds possible, although much typing involved!
C++11 enum class#
enum class#
enum class E1 {
ONE,
TWO
};
enum class E2 {
ONE,
TWO
};
E1 e1 = E1::ONE;
E2 e2 = E2::ONE;
int i = e1; // error
|
C++11 enum class: Underlying Type#
Explicit type#
#include <cstdint>
#include <cassert>
enum E: uint8_t {
ONE,
TWO
};
void f() {
assert(sizeof(E)==1);
}
|
|