简体   繁体   中英

C++ Map of string and member function pointer

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)
{
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM