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?
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.
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.