Why does the code below compile without any errors?
enum class Enumeration;
void func()
{
auto enumeration = static_cast<Enumeration>(2);
auto value = static_cast<int>(enumeration);
}
Why does the code below compile without any errors?
enum class Enumeration;
void func()
{
auto enumeration = static_cast<Enumeration>(2);
auto value = static_cast<int>(enumeration);
}
It compiles because the compiler knows at compile time the size of Enumeration
(which happens to be empty).
You see it explicitly using the following syntax:
enum class Enumeration : short;
The compiler knows everything there is to know about the Enumeration
.
Enumeration
is a opaque-enum-declaration which means also that the type is complete
i.e. you can use sizeof
on it. If needed you can specify the list of enumerators in a later redeclaration (unless the redeclaration comes with a different underlying type, obviously).
Note that since you are using enum class
usage of static_cast
is mandatory.
int
but you can safely use static_cast
on them to retrieve their integral value.They are still enum
afterall.
There are no implicit conversions from the values of a scoped enumerator to integral types, although static_cast may be used to obtain the numeric value of the enumerator.
More on this topic here: How to automatically convert strongly typed enum into int?