简体   繁体   English

需要帮助以避免向下转发

[英]need help to avoid downcasting

i created an eventhandler system simplified described by following classes 我创建了一个由以下类简化描述的事件处理程序系统

IEventType - containing string name and hashed int value of the name for fast search
IEventData - data send along with a triggered event
EventManager - containing a std::map of <int, boost::signals2< bool( boost::shared_ptr< IEventData > ) >

(there some other listeneres too for lua script side events and more, but i think thats irrelevant now) (还有一些其他的听众对于lua脚本的边缘事件和更多,但我认为现在无关紧要)

the actual problem is: when i derive an IEventData, let's say: 实际的问题是:当我派生出一个IEventData时,让我们说:

class EData_WriteToConsole : IEventData
{
  std::string text;
  int layer;
  ...
}

then i register some member function to the signal: 然后我将一些成员函数注册到信号:

OnWriteToConsole( boost::shared_ptr< IEventData > ){ ... }
m_EventManager->AddListener(boost::bind(&Console::OnWriteToConsole, m_Console, _1));

and then use the EventManager's TriggerEvent function 然后使用EventManager的TriggerEvent函数

boost::shared_ptr< EData_WriteToConsole > eventData(new EData_WriteToConsole("Text..", 1));
m_EventManager->TriggerEvent(eventData);

finally my event gets triggered: but i can't access EData_WriteToConsole specific event data because OnWriteToConsole only receives a base class IEventData ptr. 最后我的事件被触发:但我无法访问EData_WriteToConsole特定事件数据,因为OnWriteToConsole只接收基类IEventData ptr。

so i need to downcast the IEventData that boost::shared_ptr points to, into a derived class EData_WriteToConsole. 所以我需要将boost :: shared_ptr指向的IEventData转发到派生类EData_WriteToConsole。

I'm currently stuck because my brain didnt get enough sleep the last days and i just can't think of a solution without downcasting. 我现在卡住了,因为我的大脑在最后几天没有得到足够的睡眠,我只是想不出没有向下转换的解决方案。 Is there a way around this, can i somehow restructure my class hierarchy so i don't need to upcast? 有没有解决方法,我可以以某种方式重组我的类层次结构,所以我不需要upcast? (i thought about creating a std::map with data that is passed as eventdata so the receiving function can search for stuff it needs, but seems slow and silly to me) please help (我想创建一个std :: map,其数据作为eventdata传递,因此接收函数可以搜索它需要的东西,但对我来说似乎很慢而且很傻)请帮助

Could you put a virtual method in the IEventData interface eg actionEvent() that is implemented in the derived classes to call whatever is required to action the event? 你可以在IEventData接口中放置一个虚方法,例如在派生类中实现的actionEvent()来调用操作事件所需的任何内容吗?

It would restrict you a bit if the event needs to be actioned in several different ways though. 如果事件需要以几种不同的方式进行操作,它会限制你一点。

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

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