#include <iostream>#include <map>#include <string>//A typedef for our function pointer to make things easier//The return type/args can be changed at will, and you won''t//need to change any other parts of this codetypedef int (*FunctionType)(int,int);//Typedef a std::map that maps FunctionTypes to std::stringstypedef std::map<std::string,FunctionType> FunctionMap;//This will hold our data, it will map FunctionType to it''s name//as stored in a std::stringFunctionMap TheFunctionMap;//This will add a function to our mapvoid RegisterFunction(std::string& Name,FunctionType Func){ //Note that if you register a function with the same name //twice, it will overwrite the old one TheFunctionMap[Name] = Func;}//Will call the function with the matching name, using//Arg1 and Arg2. If the function is found, will return//whatever the function returns. If it is not found//returns 0. A better method should be used for telling,//the caller when the function couldn''t be found...//throwing an exception would probably be better, //but that is left as an excersise to the reader.//(If anyone reads this that is!)//int CallFunction(std::string& Name,int Arg1,int Arg2){ //First find the function in the map FunctionMap::iterator iter = TheFunctionMap.find(Name); if(iter != TheFunctionMap.end()) { //We found a function with the given name, so call it return (*iter)(Arg1,Arg2); } return 0;}//A few sample functionsvoid AddEm(int Num1,int Num2){ return (Num1+Num2);}void SubtractEm(int Num1,int Num2){ return (Num1-Num2);}void MultiplyEm(int Num1,int Num2){ return (Num1*Num2);}void DivideEm(int Num1,int Num2){ return (Num1/Num2);}int main(){ //A driver func RegisterFunction("Add",AddEm); RegisterFunction("Subtract",SubtractEm); RegisterFunction("Multiply",MultiplyEm); RegisterFunction("Divide",DivideEm); std::cout << "Calling function ''Add'' on ''5'' and ''2''...It returned " << CallFunction("Add",5,2) << std::endl; return 0;}
I don''t think that''ll compile without a couple minor changes (passing character literals when the function is expecting a string reference I think would cause it to fail), but that doesn''t really matter. The example here is kinda stupid too, but this kind of thing can be extremely useful, especially in scripting situations.