我有一些像下面這樣的任意枚舉。爲每個枚舉器添加代碼
enum MyEnumWith2Items {
Item1,
Item2
};
enum MyEnumWith3Items {
Item1,
Item2,
Item3
};
我想添加一些依賴於每個枚舉的代碼。例如,在每個項目對應的類中添加一個字段。
template<typename EnumType>
struct MyStruct {
/* magic */
};
MyStruct<MyEnumWith2Items> a; // a has the fields i1 and i2, but not i3
MyStruct<MyEnumWith3Items> b; // b has i1, i2 and i3
這可能嗎?
怎麼樣與enum class
?
如何使用static
字段或方法或任何類型的代碼?
類的定義可以採取任何形式,我的例子只是一個例子。
我可以使用任何版本的C++。
[X-macro](https://en.wikipedia.org/wiki/X_Macro)會起作用。但它很大程度上依賴於預處理器,有些人認爲它是一個醜陋的黑客。 – HolyBlackCat