454,605 Members | 1,391 Online
Need help? Post your question and get tips & solutions from a community of 454,605 IT Pros & Developers. It's quick & easy.

# switch is not optimized for mapping between enums

 P: n/a Hello, I have used some library where is defined enum like: typedef enum Enum1 { ENUM1_1, ENUM1_2, ENUM1_3, ENUM1_4, ENUM1_5 }; In my code I have defined: typedef enum Enum2 { ENUM2_1, ENUM2_2, ENUM2_3, ENUM2_4, ENUM2_5 }; My map function looks like: Enum2 mapEnum1toEnum2( Enum1 enum ) { switch( enum ) { case ENUM1_1: return ENUM2_1; case ENUM1_2: return ENUM2_2; case ENUM1_3: return ENUM2_3; case ENUM1_4: return ENUM2_4; case ENUM1_5: return ENUM2_5; default: throw "UNKNOWN ENUM1!!!"; } } I have analised asm code generated by compiler, and the results is not optimal as it can be. Because the enums can map 1:1 I have expected that compiler creates code similar to: Enum2 mapEnum1toEnum2( Enum1 enum ) { if ( enum < ENUM1_1 || enum ENUM1_5 ) throw "UNKNOWN ENUM1!!!"; return reinterpret_cast( enum ); } In example above both enums are continuous, but in case if one of enums is not continuous there is another possibility - create hash table e.g. typedef enum Enum2 { ENUM2_1 = -1, ENUM2_2 = 33, ENUM2_3 = 55, ENUM2_4 = 1234, ENUM2_5 = 5533 }; Enum2 mapEnum1toEnum2( Enum1 enum ) { static const Enum2 hash[] = { ENUM2_1, ENUM2_2, ENUM2_3, ENUM2_4, ENUM2_5 }; if ( enum < ENUM1_1 || enum ENUM1_5 ) throw "UNKNOWN ENUM1!!!"; return hash[enum]; } Do you know any implementation to create mapEnum1toEnum2 function which is better optimized than switch construction. Maybe there is possible to use metaprogramming for this issue. Best Regards MariuszC Nov 11 '06 #1