枚举和初始化类 [英] Enums and initialising classes
本文介绍了枚举和初始化类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经常遇到这个令人讨厌的怪癖.
I frequently come across this annoying quirk.
说我有类似的东西
enum class Thing {Ex1, Ex2, Ex3}
我有一个Thing实例,并且想根据它是什么来创建某个类,并且最终看起来像这样
I have an instance of a Thing and want to create a certain class depending on what it is, and it ends up looking like this
switch(_thing){
case Thing::Ex1:
ptr = new Class1();
break;
case Thing::Ex2:
ptr = new Class2();
break;
case Thing::Ex3:
ptr = new Class3();
break;
}
以此类推.用10到20个这样的语句,它看起来非常糟糕.这是不可避免的,还是有什么方法可以改善这一点?
And so on. With 10-20 such statements, it just looks very bad. Is this an inevitability, or is there some way to improve this?
推荐答案
不幸的是,C ++仍然没有反射.如果代码中有多个位置必须使用相同的值到类型的映射,则可以考虑使用久经考验的X宏:
Unfortunately, C++ still doesn't have reflection. You can consider the tried-and-true X macro, if you have multiple places in your code where you'll have to employ the same mapping of values to types:
#define CASES \
X(Thing::Ex1, Class1) \
X(Thing::Ex2, Class2) \
X(Thing::Ex3, Class3) \
// ...
// ...
switch (_thing) {
#define X(v, T) \
case (v): \
ptr = new (T)(); \
break;
CASES
#undef X
}
// ... do other things with CASES and a different X macro
// ...
#undef CASES
这篇关于枚举和初始化类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文