简体   繁体   中英

How to pass a member function as an argument?

I have the following Classes:

typedef void (*ScriptFunction)(void);
typedef std::unordered_map<std::string, std::vector<ScriptFunction>> Script_map;

class EventManager
{
public:

    Script_map subscriptions;

    void subscribe(std::string event_type, ScriptFunction handler);
    void publish(std::string event);

};

class DataStorage
{
    std::vector<std::string> data;
public:

    EventManager &em;

    DataStorage(EventManager& em);
    void load(std::string);
    void produce_words();


};
DataStorage::DataStorage(EventManager& em) : em(em) {
    this->em.subscribe("load", this->load);     
};

I want to be able to pass DataStorage::load to EventManager::subscribe so i can call it later on. How can i achieve this in c++?

The best way to do this would be with an std::function :

#include <functional>

typedef std::function<void(std::string)> myFunction;
// Actually, you could and technically probably should use "using" here, but just to follow
// your formatting here

Then, to accept a function, you need simply need to do the same thing as before:

void subscribe(std::string event_type, myFunction handler);
// btw: could just as easily be called ScriptFunction I suppose

Now the tricky part; to pass a member function, you actually need to bind an instance of DataStorage to the member function. That would look something like this:

DataStorage myDataStorage;
EventManager manager;

manager.subscribe("some event type", std::bind(&DataStorage::load, &myDataStorage));

Or, if you're inside a member function of DataStorage :

manager.subscribe("some event type", std::bind(&DataStorage::load, this));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM