How to Automatically Convert Strongly Typed Enum into Int

How to automatically convert strongly typed enum into int?

Strongly typed enums aiming to solve multiple problems and not only scoping problem as you mentioned in your question:

  1. Provide type safety, thus eliminating implicit conversion to integer by integral promotion.
  2. Specify underlying types.
  3. Provide strong scoping.

Thus, it is impossible to implicitly convert a strongly typed enum to integers, or even its underlying type - that's the idea. So you have to use static_cast to make conversion explicit.

If your only problem is scoping and you really want to have implicit promotion to integers, then you better off using not strongly typed enum with the scope of the structure it is declared in.

c++ conversion of strongly typed enums

Define the unary + operator to perform conversion to integer type.

enum RiskLevel { None, Warn, Low, High, Critical };

auto operator + ( RiskLevel value )
{ return std::underlying_type_t< RiskLevel >( value ); }

void logStuff( RiskLevel rl ) {
stringstream ss;
ss << + rl;
LOG(s);
}

void compareEnum( RiskLevel rl ) {
if ( + rl > + RiskLevel::Low ) {
...
}
}

More depth in this answer.

Type-casting enum to integer and vice versa

enum to int is unambiguous cast (assuming C++ 03 where enum is basically an int), will be performed implicitly no problem. int to enum is potentially errorneous as it's a narrowing cast, not every int value is a valid enum value. That's why casting int to enum is only possible explicitly.

Same holds for C++ 11 and later standards, with the exception that C++ 11 introduced strongly typed enums and specific size enums.

Strongly typed enum is declared enum class instead of just enum, and it cannot be converted to an integer nor any other type, save for a user-defined conversion operator or function, or brute force (static_cast). Sized enums are declared like this: enum Colors : char {...}. This particular enum's values will have char type instead of the default int.

Convert scoped enum to int

Just because such a conversion can always succeed doesn't mean you want it to be implicit.

The entire purpose of scoped enums is that they are distinct types that won't lead to confusing results during overload resolution.

Being explicit is good.

Pass strongly typed enum to function

The purpose of the c++ type system is to help tired and ADHA programmers not to mix bool and pants. (or in this case CustomCommand and char)

You must try and pass the enum "object" around as long as possible and cast only at the last point of use.
As an example you could overload the print_byte function:

void print_byte(CustomCommand  cmd)
{
std::cout << static_cast<unsigned char>(cmd);
};


Related Topics



Leave a reply



Submit