I have an enum class like this:
typedef unsigned int binary_instructions_t;
enum class BinaryInstructions : binary_instructions_t
{
END_INSTRUCTION = 0x0,
RESET,
SET_STEP_TIME,
SET_STOP_TIME,
START,
ADD
};
And I am trying to use the members of the enum in a switch statement like this:
const std::string& function(binary_instructions_t arg, bool& error_detect)
{
switch(arg)
{
case (unsigned int)BinaryInstructions::END_INSTRUCTION:
return "end";
break;
}
translate_error = true;
return "ERROR";
}
Why is the cast to (unsigned int)
required when the underlying type is already an unsigned int
?
That's because "enum class" is "strongly-typed", so not implicitly convertible to any other type. http://en.wikipedia.org/wiki/C%2B%2B11#Strongly_typed_enumerations
Because C++11 strongly typed enums are not implicitly convertible to integral types by design. The fact that the underlying type is an unsigned int
doesn't mean the type of the enum is unsigned int
. It is BinaryInstructions
.
But you don't actually need the conversion anyway Since arg
is an unsigned int, you need a cast, but you should prefer a static_cast
for clarity:
switch(arg)
{
case static_cast<unsigned int>(BinaryInstructions::END_INSTRUCTION) :
return "end";
break;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With