简体   繁体   中英

Pass member function as parameter to a parent class in a different header

Consider two classes. One being EventReceiver in a header file named events.h that defines a method Subscribe which takes in a name parameter and some callback function, and a class that derives EventReceiver in a header entities.h named Entity, that defines a method OnStart, which must be called on event named "start" in the constructor.

events.h

class EventReceiver
{
public:
    void SubscribeEvent(string name, callback_type callback);
}

entities.h

#include "events.h"

class Entity : public EventReceiver
{
public:
    Entity();
    void OnStart();
}

How would I accomplish that? What type should callback_type be to accept the OnStart function, since I can't declare it as void (Entity::*)() in EventReceiver because of a dependency loop, and can't pass a pointer to OnStart because its non-static?

If you were to go the std::function route, it'd probably look something like:

// events.h:
using callback_type = std::function<void()>;

// entities.h (the constructor):
Entity() {
    SubscribeEvent("start", [this](){ OnStart(); });
}

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