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 E1 {
ONE,
TWO
};
enum class E2 {
ONE,
TWO
};
E1 e1 = E1::ONE; // <-- ONE of E1
E2 e2 = E2::ONE; // <-- ONE of E2
int i = e1; // <-- error
No conflicts in surrounding scope
Body same as before
No conversion to
intC++03
enumremains unchanged ⟶ code compatibility⟶ Cool!
C++11 enum class: Underlying Type#
enum E: uint8_t {
ONE,
TWO
};
void f() {
assert(sizeof(E)==1);
}
In C++03
enumandenum classpossibleDefault:
intWorks with all integer types except
wchar_t
Mix: enum class With Underlying Type#
enum class E: uint8_t {
ONE,
TWO
};