C ++ Map string and member function pointer

Hey, so I'm making a map with a string as a key and a pointer to a member function as a value. I can’t figure out how to add to the map, this does not seem to work.

#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) { } 
+4
source share
1 answer

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 a member function without an object. You can use a pointer to a member function with an object of type Test

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

or pointer to type Test

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

See Also C ++ Frequently Asked Questions - Member Function Pointers

+9
source

All Articles