makurisan
makurisan

Reputation: 529

C++17 enum type declaration

I have the following enum typedef and want to define a variable which can hold the different states.

typedef enum _EventType
{
    Event1 = 0x001, Event2 = 0x002, Event2 = 0x0004
}EventType;

This it what I want:

EventType type = EventType::Event1 | EventType::Event2;

or

EventType type = EventType::Event1;
type |= EventType::Event2;

V2017 gives me the following error:

 Conversion to enumeration type requires an explicit cast (static_cast, C-style cast or function-style cast)

I know that I could write:

   EventType type = static_cast<EventType>(EventType::Event1 | EventType::Event2);

But the code is not so easy to understand.

Upvotes: 4

Views: 651

Answers (1)

user7860670
user7860670

Reputation: 37607

It is possible to overload bitor operator so it performs necessary conversions:

#include <type_traits>
#include <cstdint>

// specifying underlaying type here ensures that enum can hold values of that range
enum class EventType: ::std::uint32_t
{
    Event1 = 0x001, Event2 = 0x002, Event3 = 0x0004
};

EventType operator bitor(EventType const left, EventType const right) noexcept
{
    return static_cast<EventType>
    (
        ::std::underlying_type_t<EventType>(left)
        bitor
        ::std::underlying_type_t<EventType>(right)
    );
}

auto combined{EventType::Event1 bitor EventType::Event2};

int main()
{
}

online compiler

Upvotes: 4

Related Questions