与其包含的类类型相同的列表
A list with the same type as the class it's contained within
我正在尝试创建一个简单的事件系统,它将有许多不同的事件。因此,我尝试创建一个事件类,它允许您注册函数,获取正确类型的事件,并返回布尔值。
我想要的是,Event
的任何子类中的方法post
都将采用该子类,而不是Event
,并且每个子类中列表listeners
中的函数应该采用正确的子类类型。这是我已经拥有的代码,它强制函数转换为正确的事件类型:
事件.h:
namespace events {
class Event {
public:
static const std::List<bool (*)(Event)> listeners;
void post(Event event);
}
class ExampleEvent : Event {
int eventData;
}
}
事件.cpp:
namespace events {
void Event::post(Event event) {
for(int i = 0; i < listeners.size(); i++) {
if(listeners[i](event)) return;
}
}
}
有没有什么方法可以让它在不必执行以下操作的情况下处理子类事件?
bool handleExample(Event event) {
ExampleEvent exampleEvent = (ExampleEvent)event;
std::cout << exampleEvent.eventData << std::endl;
return false;
}
// Somewhere else in the code
ExampleEvent::listeners.push_back(&handleExample);
我为任何错误的代码道歉,我还没有完全掌握语言规则。
常用的方法是使用CRTP:
namespace events {
template<typename Derived>
class Event {
public:
static const std::list<bool (*)(Derived)> listeners;
void post(Derived event)
{
static_cast<Derived&>(*this).post(event);
}
};
class ExampleEvent : Event<ExampleEvent> {
int eventData;
void post(ExampleEvent event)
{
//implement post
}
};
}
只需使用虚拟函数:
namespace events {
class EventHandler {
public:
static const std::list<Event*> listeners;
void post() {
for (Event * listener : listeners) {
if (listener->post()) break;
}
}
};
class BaseEvent {
public:
virtual bool post() = 0;
virtual ~BaseEvent() {}
};
class ExampleEvent : public BaseEvent { // use public inheritance
int eventData;
public:
virtual bool post() override {
if (eventData == 0) return true;
return false;
}
};
}
相关文章:
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 使用简单类型列表实现的指数编译时间.为什么
- 使用模板类的自定义列表类型中的内存泄漏
- 列表参数的类型定义
- 初始值设定项列表是否只接受使用相同类型的值初始化变量?
- 从类型列表中递归删除重复项会导致编译器堆空间错误 (VS2017)
- C++模板/别名 - 模板参数列表中参数 1 处的类型/值不匹配
- 如何使用类型别名从模板化类中隐藏模板列表
- 测试两个类型列表中的所有组合
- 错误:"模板<类_Tp,类_Dp>类 std::unique_ptr"的模板参数列表中参数 1 的类型/值不匹配
- 谷歌测试:模板模板的笛卡尔乘积的类型列表与模板
- 在迭代模板类型列表时无法停止递归
- 将可变参数类型列表的扩展打包为复杂类型的初始值设定项列表 - 合法吗?
- 使用"auto"推断嵌套初始值设定项列表的类型
- lamda 中的不同类型,在捕获列表中引用
- 阅读从 istream 到矢量的不同类型列表
- 在模板元编程中使用列表类型
- 接受泛型列表类型对象的参数
- 删除c++中列表类型的数组的元素
- 在系统列表中列出::集合::通用::列表<T>类型是可能的吗?