Hi friends,

Can you please help me with the syntax of how I will map a string to a function pointer using map stl?


#include <iostream>
#include <map>
#include <string>

std::string foo() { return "Foo"; }
std::string bar() { return "Bar"; }

int main()
  std::map<std::string, std::string (*)()> m;

  // Map the functions to the names
  m["foo"] = &foo;
  m["bar"] = &bar;

  // Display all of the mapped functions
  std::map<std::string, std::string (*)()>::const_iterator it = m.begin();
  std::map<std::string, std::string (*)()>::const_iterator end = m.end();

  while ( it != end ) {
    std::cout<< it->first <<"\t\""
      << (it->second)() <<"\"\n";

Fire point-blank:

#include <iostream>
#include <string>
#include <map>
using namespace std;

namespace // for example only
void DoOne() { cout << "One" << endl; }

void DoTwo() { cout << "Two" << endl; }

void DoNil() { cout << "Nil" << endl; }

void Mapper()
    typedef void (*DoIt)();
    typedef map<string,DoIt> MapCall;

    MapCall	doit;


    MapCall::const_iterator call;

    call = doit.find("One");
    if (call != doit.end())
       cout << "Unknown call requested" << endl;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.