0

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

Josty
  • 7
  • 2
  • 1
    There's a [difference](https://stackoverflow.com/questions/18229638/function-pointer-as-a-member-of-a-class) between a function pointer and a member function pointer. What you want to do is covered under various [callback](https://stackoverflow.com/questions/3098085/efficient-method-of-passing-callback-member-function) questions. – 1201ProgramAlarm Oct 28 '19 at 03:11

1 Answers1

1

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));
  • Thanks. Fixed the typedef. I get that mixed up sometimes. –  Oct 28 '19 at 17:40
  • Also, good point about the lambdas. It might be worth creating an answer yourself with. Otherwise I get credit for it. –  Oct 28 '19 at 17:42