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 | } |