[英]How to create an unordered_map for string to function
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? 有没有其他方法可以使用MyObject :: printSomeText函数作为该对的值?
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. 这只允许您在当前实例上调用成员函数,而不是在任何给定的MyObject
实例上调用。 If you want the extra flexibility, make the mapped type a std::pair<MyObject*, void(MyObject::*)()>
instead. 如果您想要额外的灵活性,请将映射类型改为std::pair<MyObject*, void(MyObject::*)()>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.