Gasim
Gasim

Reputation: 7961

scoped but "semi-weakly" typed enumerations

I want to use enumerations in a scoped format but be able to do comparison and assignment between the enumeration and unsigned integers.

This is what I have tried the code below, which works as expected:

class SystemEvents {
public:
    enum {
        Opened, Closed
    };
};

class OtherEvents {
public:
  enum {
     Closed,Opened
  };
};

//test
uint32_t e = SystemEvents::Opened;
if(e == OtherEvents::Closed) std::cout << "enums are weakly typed and scoped"; 

But I want to know if there is a way of doing it with the C++11 syntax?

enum class SystemEvents : uint32_t {
   Opened,Closed
};

enum class OtherEvents : uint32_t {
   Closed,Opened
};

//test
uint32_t e = SystemEvents::Opened;
if(e == OtherEvents::Closed) std::cout << "enums are weakly typed and scoped"; 

The code above gives me error as expected Cannot initialize a variable of type int with an rvalue of type SystemEvents. So, Should I stick with the C style scoped enumerations or is there a way of doing it in C++11? Or is there some other way of doing this?

Upvotes: 4

Views: 328

Answers (2)

Daniel Frey
Daniel Frey

Reputation: 56863

For the initialization there is not much you can do other than cast the value. Note that C++11's strongly typed enums are not meant to replace but rather complement the existing enums. If you want a weakly-typed enum, just don't use enum class.

For the comparison of a strongly-typed enum, you can declare the necessary operators and cast inside the implementation:

bool operator==( uint32_t lhs, SystemEvents rhs )
{
    return static_cast< SystemEvent >( lhs ) == rhs;
}

Of course you need both directions:

bool operator==( SystemEvents lhs, uint32_t rhs );

And other operators like !=.

Upvotes: 3

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

You can explicitly cast an enum class to an integral type, for example:

static_cast<uint32_t>(SystemEvents::Opened)

You could also write a function that will cast to the underlying type of any enum class.

However, needing to do this suggests that you're doing something wrong. Why are you trying to compare SystemEvents with OtherEvents?

Upvotes: 1

Related Questions