我有一些像下面这样的任意枚举。为每个枚举器添加代码
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