C++ 用于获取枚举值的名字 Post author:xfxia Post published:2023年12月26日 Post category:其他 template < class Child> 02 class EnumBase 03 { 04 protected : 05 //typedef typename Child::Et Et; 06 struct EnumProperty 07 { 08 const char * mName; 09 int mEt; 10 }; 11 12 public : 13 14 static int toEnum( const char * name) 15 { 16 int size = 0; 17 const EnumProperty * pP = Child::getEnumPropertys(size); 18 for ( int iter = 0;iter < size ; ++ iter) 19 { 20 if ( strcmp (pP[iter].mName,name) == 0) 21 return pP[iter].mEt; 22 } 23 return 0; 24 } 25 26 static const char * toString( int et) 27 { 28 int size = 0; 29 const EnumProperty * pP = Child::getEnumPropertys(size); 30 for ( int iter = 0;iter < size ; ++ iter) 31 { 32 if (pP[iter].mEt == et) 33 return pP[iter].mName; 34 } 35 return 0; 36 } 37 }; 38 39 #define TOSTRING(t) #t 40 #define MAP_TO_STRING(ot) TOSTRING(ot),ot 41 42 class DamageType : public EnumBase<DamageType> 43 { 44 public : 45 enum Et{ 46 Wood = 0x01, 47 Stone = 0x02, 48 Metal = 0x04, 49 Ice = 0x08, 50 Other = 0x10, 51 DamageAdditionEnd = 0x20, 52 }; 53 struct x{}; 54 55 static const EnumProperty* getEnumPropertys( int &size) 56 { 57 const static EnumProperty __[] = 58 { 59 {MAP_TO_STRING(Wood)}, 60 {MAP_TO_STRING(Stone)}, 61 {MAP_TO_STRING(Metal)}, 62 {MAP_TO_STRING(Ice)}, 63 {MAP_TO_STRING(Other)}, 64 }; 65 66 size = sizeof (__)/ sizeof (__[0]); 67 return __; 68 } 69 }; 70 int main() 71 { 72 printf ( "%d\n" ,DamageType::toEnum( "Wood" )); 73 printf ( "%d\n" ,DamageType::toEnum( "Stone" )); 74 printf ( "%d\n" ,DamageType::toEnum( "Metal" )); 75 printf ( "%d\n" ,DamageType::toEnum( "Ice" )); 76 printf ( "%d\n" ,DamageType::toEnum( "Other" )); 77 78 printf ( "%s\n" ,DamageType::toString(DamageType::Wood)); 79 printf ( "%s\n" ,DamageType::toString(DamageType::Stone)); 80 printf ( "%s\n" ,DamageType::toString(DamageType::Metal)); 81 printf ( "%s\n" ,DamageType::toString(DamageType::Ice)); 82 printf ( "%s\n" ,DamageType::toString(DamageType::Other)); 83 return 0; 84 } 你可能也喜欢 异常将上下文初始化事件发送到类的侦听器实例[org.springframework.web.context.ContextLoaderListener] 无线模块的参数介绍和选型要点 the system can not open the device or file specified解决方案 Bellman Ford算法详解 线段树专题(二) Mybatis中实体类属性和数据列之间映射的四种办法 LVS三种工作模式(NAT、DR、TUN)原理及配置 洛谷试炼场—普及练习场 C++ string 的使用 iOS APP优化之–IPA体积优化 在Ubuntu下解压.zip文件发现中文乱码问题 Web项目部署到TongWeb的注意事项,TongWeb踩过的坑 hmc如何进入aix系统_如何进入PE系统(微PE) 四元数、罗德里格斯公式、欧拉角、旋转矩阵推导和资料 根轨迹和系统参数的确定 编译器——指令的汇编 JS中 for in 与 for of的区别 Uni.app知识点 Ubuntu下,在桌面创建.sh文件快捷方式 【node.js】http.createServer与http.Server对比