Ith*_*din 5 c++ templates casting event-handling
我正在为游戏实现一个事件系统.它使用事件队列和数据结构来保存给定事件类型的所有已注册事件处理程序.它到目前为止注册处理程序工作得很好,但是当取消注册它们时(例如,当游戏对象被销毁时会发生这种情况)我在模板和转换方面遇到了一些麻烦.
我已经将EventHandler定义为某种函子,部分基于Szymon Gatner在http://www.gamedev.net/reference/programming/features/effeventcpp/上的文章.确切地说,我使用了HandlerFunctionBase和MemberFunctionHandler类定义并提出了:
class BaseEventHandler
{
public:
virtual ~BaseEventHandler(){}
void handleEvent(const EventPtr evt)
{
invoke(evt);
}
private:
virtual void invoke(const EventPtr evt)=0;
};
template <class T, class TEvent>
class EventHandler: public BaseEventHandler
{
public:
typedef void (T::*TMemberFunction)(boost::shared_ptr<TEvent>);
typedef boost::shared_ptr<T> TPtr;
typedef boost::shared_ptr<TEvent> TEventPtr;
EventHandler(TPtr instance, TMemberFunction memFn) : mInstance(instance), mCallback(memFn) {}
void invoke(const EventPtr evt)
{
(mInstance.get()->*mCallback)(boost::dynamic_pointer_cast<TEvent>(evt));
}
TPtr getInstance() const{return mInstance;}
TMemberFunction getCallback() const{return mCallback;}
private:
TPtr mInstance;
TMemberFunction mCallback;
};
Run Code Online (Sandbox Code Playgroud)
然后我想到的EventManager类上的unregisterHandler()方法的初始实现将如下所示:
// EventHandlerPtr is a boost::shared_ptr<BaseEventHandler>.
// mEventHandlers is an STL map indexed by TEventType, where the values are a std::list<EventHandlerPtr>
void EventManager::unregisterHandler(EventHandlerPtr hdl,TEventType evtType)
{
if (!mEventHandlers.empty() && mEventHandlers.count(evtType))
{
mEventHandlers[evtType].remove(hdl);
//remove entry if there are no more handlers subscribed for the event type
if (mEventHandlers[evtType].size()==0)
mEventHandlers.erase(evtType);
}
}
Run Code Online (Sandbox Code Playgroud)
为了使"删除"工作在这里,我想到为BaseEventHandler重载==运算符,然后使用虚方法来执行实际比较...
bool BaseEventHandler::operator== (const BaseEventHandler& other) const
{
if (typeid(*this)!=typeid(other)) return false;
return equal(other);
}
Run Code Online (Sandbox Code Playgroud)
并且,在模板类EventHandler上,实现抽象方法'equal',如下所示:
bool equal(const BaseEventHandler& other) const
{
EventHandler<T,TEvent> derivedOther = static_cast<EventHandler<T,TEvent>>(other);
return derivedOther.getInstance() == this->getInstance() && derivedOther.getCallback()==this->getCallback();
}
Run Code Online (Sandbox Code Playgroud)
当然,我在static_cast行上遇到编译错误.我甚至不确定是否可以进行演员表演(不一定使用static_cast).有没有办法执行它,或者至少有一些解决方法可以解决这个问题?
在此先感谢=)
一般来说,关闭模板时,您需要确保 > 用空格分隔,以便编译器不会将它们解析为右移运算符。
在这里,您尝试将引用静态转换为非引用,即使它有效也可能会调用对象切片。您需要静态转换为派生引用。
bool equal(const BaseEventHandler& other) const
{
EventHandler<T,TEvent>& derivedOther = static_cast<EventHandler<T,TEvent>&>(other);
return derivedOther.getInstance() == this->getInstance() && derivedOther.getCallback()==this->getCallback();
}
Run Code Online (Sandbox Code Playgroud)