[英]Is it possible to hold multiple types of enums in a variable in C++?
是否可以在 C++ 中做這樣的事情:
enum A {//Starts from 0 and has no enum with out of place value like 0,1,5,40, etc.
eg1,
eg2,
eg3,
...
}
enum B {//Same structure as enum A
e1,
e2,
e3,
...
}
some_data_type e = eg1;//No errors here
e = e2;//No errors here
我認為它可能只是一個 integer,但為了安全起見,還有其他方法可以做到這一點嗎?
在 C++17 及更高版本中,您可以使用std::variant
:
enum A {//Starts from 0 and has no enum with out of place value like 0,1,5,40, etc.
eg1,
eg2,
eg3,
...
}
enum B {//Same structure as enum A
e1,
e2,
e3,
...
}
std::variant<A,B> e = eg1;
e = e2;
如果您可以忽略原始類型之間的區別,那么 integer 將起作用。 如果您想要更嚴格一點並且只允許對“兼容”枚舉進行賦值和比較,那么可能需要一個用戶定義的類型,該類型具有來自A
和B
的隱式轉換。 不幸的是,您不能直接在兩個枚舉之間添加轉換,因為轉換函數和轉換構造函數都必須是成員函數,而枚舉不允許。
如果您想稍后區分它們,那么boost::variant<A, B>
會這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.