Here is a possible solution. Use a STL map. The key will be the STL string that has the function name, and it will hold the function pointers.
So once at the start of your program you add all the functions to the map, which i called lookuptable, then when you read in the string simply search the look up table using the [] operator.
If you want more info on a map check out http://www.sgi.com/tech/stl/Map.html
On a side note, when i compile this code it runs fine, but i get about 98 warnings dealing with STL crap. I know there is some option to turn the warning off. Back in CS2 we did
#pragma SomeOptionHere
and it had a 4 digit number in it, i believe. Anyone know what im talking about, or how to remove these stupid STL warnings?
Code:
#include <iostream>
#include <string>
#include <map>
using namespace std;
int (*fPtr)(int, int);
int Add(int a,int b);
int Sub(int a,int b);
//key is a string
//data type is a pointer to a function that returns 1 int, and takes 2 ints has parameters
map<string, int(*)(int,int)> LookUpTable;
int main()
{
//place all functions into look up table
LookUpTable["Add"] = Add;
LookUpTable["Sub"] = Sub;
//function that we want
string function = "Add";
//find it in the look up table
fPtr = LookUpTable["Add"];
//call the add function from the function pointer we got from the look up table
cout << fPtr(1,2) << endl; //this will print out 3 (1+2=3)
//call the sub function directly from the look up table
cout << LookUpTable["Sub"](2,1) << endl; //this will print out 1 (2-1=1)
//the look up table will return null if the search key cannot be found
fPtr = LookUpTable["Not In Here"];
if( fPtr == NULL )
{
cout << "its null";
}
return 0;
}
int Add(int a,int b)
{
return a+b;
}
int Sub(int a,int b)
{
return a-b;
}