Using Input String to Call Function with Same Name

Is it possible to call a function based on a given string?

For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;

void male() {
cout << "Male";
}

void female() {
cout << "Female";
}

int main ()
{
  string mystr;
  cout << "Enter male/female ";
  getline (cin, mystr);
  mystr();
  return 0;
}


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!
Ok, with dynamic loading of DLL/so, yes, but that is probably beyond your scope.

Otherwise, no, you need explicit comparisons

if( mystr == "male" )
male();
else ...
Thanks for the reply.

I thought as much. Thankfully, my program is only limited to a few strings/functions. =)
Hello, I'm trying to do something like this.

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?

Thanks in advance
No, see above.
What you are trying to do is common. Use a lookup table.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <string>
using namespace std;

void male()
  {
  cout << "I'm a man.\n";
  }

void female()
  {
  cout << "I'm a woman.\n";
  }

struct
  {
  (void)(*fn)();
  const char* 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))();
      return true;
      }
  return false;
  }

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.)

Variations abound.

Hope this helps.
Topic archived. No new replies allowed.