C++ C++;17枚举类型声明

C++ C++;17枚举类型声明,c++,c++17,C++,C++17,我有下面的enum typedef,希望定义一个可以保存不同状态的变量 typedef enum _EventType { Event1 = 0x001, Event2 = 0x002, Event2 = 0x0004 }EventType; 这就是我想要的: EventType type = EventType::Event1 | EventType::Event2; 或 V2017给了我以下错误: Conversion to enumeration type requires

我有下面的enum typedef,希望定义一个可以保存不同状态的变量

typedef enum _EventType
{
    Event1 = 0x001, Event2 = 0x002, Event2 = 0x0004
}EventType;
这就是我想要的:

EventType type = EventType::Event1 | 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);
EventType type=static_cast(EventType::Event1 | EventType::Event2);

但代码并不容易理解。

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

#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()
{
}
#包括
#包括
//在此处指定参考底图类型可确保枚举可以保存该范围的值
枚举类事件类型:::std::uint32\u t
{
事件1=0x001,事件2=0x002,事件3=0x0004
};
EventType运算符位(EventType常量左、EventType常量右)无异常
{
返回静态输出
(
::std::基础类型(左)
比特
::std::基础类型(右)
);
}
自动组合{EventType::Event1位或EventType::Event2};
int main()
{
}

每个有效枚举值都有一个位集。当您尝试将它们与
|
组合时,您不再具有枚举中的值,因此您应该无法通过强制执行系统(
static\u cast
等)将它们分配给枚举类型的变量。变量应该是“代码> int <代码>,除非有其他人有更好的想法。请注意<代码> C.事件类型< /C>是保留标识符,因为它从下划线开始,然后是大写。注意,<>代码> TyPulfEnUm…<代码>只在C++中使用,可以做<代码>枚举EnvivType {…};代码>用于删除typedef的Tnx!还有一件事。这是怎么回事;“类型|=事件类型::事件2;”。这也是可能的吗?怎么可能?@makurisan其他操作符也会过载。是的,我知道,我也尝试过,但第一次没有成功。现在它起作用了。
#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()
{
}