C++ Map of string and member function pointer

user1670407 picture user1670407 · Jan 19, 2013 · Viewed 12.5k times · Source

Hey so I am making a map with string as the key and a member function pointer as the value. I can't seem to figure out how to add to the map, this doesn't seem to be working.

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

typedef string(Test::*myFunc)(string);
typedef map<string, myFunc> MyMap;


class Test
{
private:
    MyMap myMap;

public:
    Test(void);
    string TestFunc(string input);
};





#include "Test.h"

Test::Test(void)
{
    myMap.insert("test", &TestFunc);
    myMap["test"] = &TestFunc;
}

string Test::TestFunc(string input)
{
}

Answer

Olaf Dietsche picture Olaf Dietsche · Jan 19, 2013

See std::map::insert and std::map for value_type

myMap.insert(std::map<std::string, myFunc>::value_type("test", &Test::TestFunc));

and for operator[]

myMap["test"] = &Test::TestFunc;

You cannot use a pointer to member function without an object. You can use the pointer to member function with an object of type Test

Test t;
myFunc f = myMap["test"];
std::string s = (t.*f)("Hello, world!");

or with a pointer to type Test

Test *p = new Test();
myFunc f = myMap["test"];
std::string s = (p->*f)("Hello, world!");

See also C++ FAQ - Pointers to member functions