Quote:Original post by Servant of the Lord
Thanks. That seems rather chunky for what seems like a simple thing. Someone should create a varation of switch which acepts most variables.
Some languages offer a construct along these lines, but generally also do not provide fall-through of cases (used normally only when you want the same logic for multiple case values). At this point, it basically becomes syntactic sugar for an if/else-if chain.
The mapping illustrated by Evil Steve is backwards: if you have a string, then you want a map from string to Direction: reverse the types in the declaration, and the items in the initialization (thus stringMap["North"] = North;).
The approach with function objects looks like this, and avoids switch statements altogether:
class DirectionAction { virtual void operator()();};class NorthAction : public DirectionAction { void operator()() { // insert logic for going north here. }};// etc.// HOWEVER, do note that because these are *objects*, you can instantiate them// several times, and also give them member data. If the logic for going in any// given direction is effectively the same, then you might just use one class,// with a "direction" data member that is initialized by a constructor and// consulted by the operator()().std::map<std::string, DirectionAction*> mapping;// If you can avoid inheritance altogether by the above technique, then you// can store plain objects here and avoid the memory management headache.mapping["North"] = new NorthAction();// etc.std::map<Direction, std::string>::iterator it = stringMap.find(input);if (it != stringMap.end()) { (*it->second)();}// That is, dereference the iterator to get a key/value pair, select the value// (which is a DirectionObject*), dereference the pointer to get the object,// and "call the object" (invoke its operator()()). Look ma, no switch.
You should probably read
this as well.