我有以下枚举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);
但是代码不是那么容易理解。
最佳答案
可以重载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