C ++ 17枚举类型声明

时间:2019-01-26 07:49:27

标签: c++ c++17

我具有以下枚举typedef,并且想要定义一个可以容纳不同状态的变量。

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

这就是我想要的:

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

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

V2017给我以下错误:

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

我知道我会写:

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

但是代码不是那么容易理解。

1 个答案:

答案 0 :(得分:4)

可以重载bitor运算符,以便执行必要的转换:

#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