[英]C++17 enum type declaration
我有以下枚舉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()
{
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.