1 year ago

#340935

test-img

roschach

How to raise error/warning when static_cast-ing values outside the set of enum class

Consider the case where I have to convert an int type to an enum. When doing this with static_cast the risk is that even values out of admissible values of the enum are casted. Take as example the following code:

#include<iostream>

int main(char argc, char* argv[])
{
  enum class EnumType : uint8_t
  {
    A = 0,
    B = 1,
    default=255
  };

  EnumType enum_var;
  uint8_t num_var_out_of_range = 31;
  enum_var = static_cast<EnumType>(num_var_out_of_range);
  std::cout<<static_cast<int>(enum_var)<<std::endl;
  return 0;
}

31 is not in the set of the enum values. I guess that the cast is valid because the underlying type of the enum is able to represent that value, but in my opinion it would more appropriate to raise an error or warning in this case. Is there a way to manage such cases?

c++

enums

casting

static-cast

0 Answers

Your Answer

Accepted video resources