Fun C++ code
As a programmer I will sometimes do some code because I feel it works out the best with minimal effort, also trying to adhere to the KISS principal (Keep it Simple Stupid).
One of the things I have been abusing as of late is the STL Map object. I have the following need: I have to take in user input from a socket (I use a socket object I wrote here, that works just like cin and cout) and I need to run one of many functions. All the functions have the same function signature. so lets assume that a function looks like this
[code]
void function(void *);
[/code]
First I know void pointers, but I am only doing an example so don’t freak out. Now back to it. Now lets say you have 20 to 40 functions like this. And you will pick one based on the input that comes in from the user via a socket connection. the incoming info is plain text, it could be read in from a command line for all I care. A fast way to pick the right function (IMO) is to use a STL Map object. So I would declare the object in the following way
[code]
std::map
[/code]
filling the map object is easy
[code]
FunctionPicker[“function1”] = &function;
FunctionPicker[“function2”] = &printingFunction;
[/code]
Running a function after getting is easy, also remember if the index into map does not exist it return 0 or in the case of a function pointer we can check for NULL. So you want a variable declared in the following way.
[code]
void (*funPtr)(void *); // Yes I know funPtr is not all that creative
// of a name but it gives an idea what it does
[/code]
So to get the function pointer from the map and run the function you would want to do the following.
[code]
funPtr = FunctionPicker[userinput]; // lets assume that userinput is declard as
// std::string
if(funPtr == NULL)
{
// put some error handling code here
}
(*funPtr)(); // since funPtr is now a pointer to the
// function we want to run, we need to
// deference it and then call it
[/code]
Now is that not easy and we let the coders that wrote the STL do the hard work for us, and we don’t have an ugly if, else if, else tree in the code. Plus adding a new function is as easy as writing the code for the new function, and adding the entry to the Map object.
I would love to see what others have done to deal with this situation. Or what is your favorite programming tool you use or abuse.