I'm trying to come up with a better solution than the one shown below to match one data type to another. Frequently I see code such as below where a switch is done in order to match one type to another. The example shows two enums but they need not be.
I've also come across situations where 'just by chance' the two enums match up and therefore a simple = is used.Code:#include <iostream> using namespace std; enum color { BLUE = 0, RED, GREEN, YELLOW }; enum object { APPLE = 0, SKY, FIRE, SUN }; object color_2_object(unsigned char color); color object_2_color(unsigned char object); int main(void) { object object1; color color1; cout << "Hello\n"; object1 = color_2_object(YELLOW); cout << "color YELLOW matches object: " << object1 << "\n"; color1 = object_2_color(APPLE); cout << "object APPLE matches color: " << color1 << "\n"; } object color_2_object(unsigned char color) { object local_object = SKY; switch(color) { case BLUE: local_object = SKY; break; case RED: local_object = FIRE; break; case GREEN: local_object = APPLE; break; case YELLOW: local_object = SUN; break; default: break; } return local_object; } color object_2_color(unsigned char object) { color local_color = GREEN; switch(object) { case APPLE: local_color = GREEN; break; case SKY: local_color = BLUE; break; case FIRE: local_color = RED; break; case SUN: local_color = YELLOW; break; default: break; } return local_color; }
My concern is when or if one or both of the data types are changed. Multiple places (switches) must be changed and I'm trying to think of a good way to avoid this. Is the only solution to create these type of conversion or matching routines? I only tend to need to do the conversion once and therefore a procedure seems a little wasteful. However on the other hand there are many of these data types which I need to convert and I don't like adding many switches in the code.Code:enum color { BLUE = 0, RED, GREEN, YELLOW }; enum object { SKY = 0, FIRE, APPLE, YELLOW }; color1 = (color)object1;
I've used some simple c++ here so please excuse!
TIA



LinkBack URL
About LinkBacks



CornedBee