joels
joels

Reputation: 7711

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?

Upvotes: 0

Views: 355

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477010

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.

Upvotes: 2

Related Questions