0
class MyObject{ public: void testFunctionMap(){ std::unordered_map<std::string, std::function<void()> > functionMap; std::pair<std::string, std::function<void()> > myPair("print", std::bind(&MyObject::printSomeText, this) ); functionMap.insert( myPair ); functionMap["print"](); } void printSomeText() { std::cout << "Printing some text"; } }; MyObject o; o.testFunctionMap(); 

This works fine. Is there another way to use the MyObject::printSomeText function as the value for the pair?

1 Answer 1

2

Yes, a pointer-to-member-function:

std::unordered_map<std::string, void(MyObject::*)()> m; m["foo"] = &MyObject::printSomeText; // invoke: (this->*m["foo"])(); 

This only allows you to call the member function on the current instance, rather than on any given MyObject instance. If you want the extra flexibility, make the mapped type a std::pair<MyObject*, void(MyObject::*)()> instead.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.