In the code below, I use static_cast
to convert an strongly typed enum
to an int
. The same works in the other direction. But it also works if the cast int
is not within the range of the enum
. Why is that and why is the compiler not catching this?
#include <iostream>
#include <string>
enum class Name {Hans, Peter, Georg}; // 0, 1, 2
std::string getName(Name name) {
switch(name) {
case Name::Hans: return "Hans";
case Name::Peter: return "Peter";
case Name::Georg: return "Georg";
default: return "not valid name";
}
}
int main()
{
// Cast a Name to an int, works fine.
std::cout<< static_cast<int>( Name::Peter ) <<std::endl; // 1
std::cout<< static_cast<int>( Name::Hans ) <<std::endl; // 0
// Cast an int to a Name
std::cout<< getName(static_cast<Name>(2)) <<std::endl; // Georg
std::cout<< getName(static_cast<Name>(3)) <<std::endl; // not a valid name
// I would expect a compiler error/warning like i get here:
// std::cout<< static_cast<int>( Name::Hans + 4 ) <<std::endl;
}