简体   繁体   中英

static_cast on integer to enum conversion

There is some function that takes in an enum as argument

void myfunc(myEnum input);

As I understand, if I have to give an integer to this function, it is advised to explicitly cast it to enum, the reason being all integers may not be valid enum values.

As per MSDN

"The static_cast operator can explicitly convert an integral value to an enumeration type. If the value of the integral type does not fall within the range of enumeration values, the resulting enumeration value is undefined."

and as per the C++ standards 5.2.9 Static cast -> 10

"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 value is unspecified (and might not be in that range)."

So what's the point using static_cast in this scenario? Is there some option that would raise exceptions on values outside the enum range (other than writing explicit code for that)?

As usual, the compiler is just trying to keep you from shooting yourself in the foot. That's why you cannot just pass an int to a function expecting an enum. The compiler will rightfully complain, because the int might not match any valid enum value.

By adding the cast you basically tell the compiler 'Shut up, I know what I am doing' . What you are communicating here is that you are sure that the value you pass in is 'within the range of the enumeration values'. And you better make sure that is the case, or you are on a one-way trip to undefined-behavior-land.

If this is so dangerous, then why doesn't the compiler add a runtime check for the integer value? The reason is, as so often with C++, performance. Maybe you just know from the surrounding program logic that the int value will always be valid and you absolutely cannot waste any time on stupid runtime checks. From a language-design point of view, this might not be the most reasonable default to chose, especially when your goal is writing robust code. But that's just how C++ works: A developer should never have to pay for functionality that they might not want to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM