将成员函数作为参数传递给不同 header 中的 parent class
Pass member function as parameter to a parent class in a different header
考虑两个 classes。一个是名为 events.h
的 header 文件中的 EventReceiver,它定义了一个接受名称参数和一些回调函数的 Subscribe 方法,以及一个 class 在 header 中派生 EventReceiver entities.h
名为 Entity,它定义了一个方法 OnStart,必须在构造函数中名为 "start"
的事件上调用该方法。
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();
}
我将如何做到这一点? callback_type
应该是什么类型才能接受 OnStart 函数,因为由于依赖循环,我无法在 EventReceiver
中将其声明为 void (Entity::*)()
,并且无法将指针传递给 OnStart
因为它 non-static?
如果你走 std::function
路线,它可能看起来像:
// events.h:
using callback_type = std::function<void()>;
// entities.h (the constructor):
Entity() {
SubscribeEvent("start", [this](){ OnStart(); });
}
考虑两个 classes。一个是名为 events.h
的 header 文件中的 EventReceiver,它定义了一个接受名称参数和一些回调函数的 Subscribe 方法,以及一个 class 在 header 中派生 EventReceiver entities.h
名为 Entity,它定义了一个方法 OnStart,必须在构造函数中名为 "start"
的事件上调用该方法。
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();
}
我将如何做到这一点? callback_type
应该是什么类型才能接受 OnStart 函数,因为由于依赖循环,我无法在 EventReceiver
中将其声明为 void (Entity::*)()
,并且无法将指针传递给 OnStart
因为它 non-static?
如果你走 std::function
路线,它可能看起来像:
// events.h:
using callback_type = std::function<void()>;
// entities.h (the constructor):
Entity() {
SubscribeEvent("start", [this](){ OnStart(); });
}