Hopefully this is enough of an example to show you what I'm looking for. Basically, whatever mystr is will match the name of a function and I need it to call that particular function. Thanks!
I have a server wich contains the object server with an attribute "a".
When a client request the content of "a" the request of the client is "server.a", so if I save this as an string in the server then i just have to call this string. Could I do this?
#include <iostream>
#include <string>
usingnamespace std;
void male()
{
cout << "I'm a man.\n";
}
void female()
{
cout << "I'm a woman.\n";
}
struct
{
(void)(*fn)();
constchar* key;
}
function_lookup_table[] =
{
{ &male, "male" },
{ &female, "female" },
{ NULL, NULL }
};
bool lookup_and_call( const string& name )
{
for (int i = 0; function_lookup_table[ i ].fn; i++)
if (name == function_lookup_table[ i ].key)
{
(*(function_lookup_table[ i ].fn))();
returntrue;
}
returnfalse;
}
int main()
{
string users_gender;
cout << "Enter male or female> " << flush;
getline( cin, users_gender );
if (!lookup_and_call( users_gender ))
{
cout << "What?\n";
}
return 0;
}
This is not the only way, or even necessarily the best way, to do this, but it is simple and works in both C and C++. See The Function Pointer Tutorials http://www.newty.de/fpt/index.html
for more on using function pointers.
Another answer would be to use an array of descendant classes which identify themselves based upon the input. (C++ only.)