Strongly Typed enum
¶
C++03 enum
Types: Motivation¶
Why enum
? Why isn’t int
sufficient?
Readability, Semantics
switch
statements withoutdefault
label ⟶-Wswitch
warns about missing enumeratorsType safety:
int
cannot be assigned to anenum
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 scopeRather, they pollute the surrounding scope
⟶ no two enumerators with the same name
Underlying type is not defined ⟶
sizeof
depends 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;
E2 e2 = E2::ONE;
int i = e1; // error
|
C++11 enum class
: Underlying Type¶
#include <cstdint>
#include <cassert>
enum E: uint8_t {
ONE,
TWO
};
void f() {
assert(sizeof(E)==1);
}
|
|