简体   繁体   English

将成员函数作为参数传递给不同标头中的父类

[英]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的头文件中的 EventReceiver,它定义了一个方法 Subscribe,它接受一个名称参数和一些回调函数,以及一个在名为 Entity 的头entities.h中派生 EventReceiver 的类,它定义了一个方法 OnStart,它必须在构造函数中名为"start"事件上调用。

events.h事件.h

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

entities.h实体.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? callback_type应该是什么类型来接受 OnStart 函数,因为由于依赖循环,我不能在EventReceiver其声明为void (Entity::*)() ,并且不能传递指向OnStart的指针,因为它是非静态的?

If you were to go the std::function route, it'd probably look something like:如果你要走std::function路线,它可能看起来像:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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