For this particular type of cast (integral to enumeration type), an exception might be thrown.
C++ standard 5.2.9 Static cast [expr.static.cast] paragraph 7
A value of integral or enumeration type can be explicitly converted to
an enumeration type. The value is unchanged if the original value is
within the range of the enumeration values (7.2). Otherwise, the
resulting enumeration value is unspecified / undefined (since C++17).
Note that since C++17 such conversion might in fact result in undefined behavior, which may include throwing an exception.
In other words, your particular usage of static_cast
to get an enumerated value from an integer is fine until C++17 and always fine, if you make sure that the integer actually represents a valid enumerated value via some kind of input validation procedure.
Sometimes the input validation procedure completely eliminates the need for a static_cast
, like so:
animal GetAnimal(int y)
{
switch(y)
{
case 1:
return CAT;
case 2:
return DOG;
default:
// Do something about the invalid parameter, like throw an exception,
// write to a log file, or assert() it.
}
}
Do consider using something like the above structure, for it requires no casts and gives you the opportunity to handle boundary cases correctly.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…