简体   繁体   English

C ++ 17枚举类型声明

[英]C++17 enum type declaration

I have the following enum typedef and want to define a variable which can hold the different states. 我有以下枚举typedef,并希望定义一个可以保存不同状态的变量。

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: V2017给我以下错误:

 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. 但代码并不那么容易理解。

It is possible to overload bitor operator so it performs necessary conversions: 可以使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 在线编译器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM