I am trying to implement a typeafe event bus. I am stuck in the EventBus::subscribe
function because it does not accept my specific event handler. In an earlier version, I had AbstractEventHandler
implemented only as an abstract class, without a template. I had no problems with this implementation. Therefore, I assume that the actual problem is related to the abstract pattern.
The code below is a stripped down version of my implementation. The first block consists of the "skeleton" of the event bus and its required classes, while the second block shows the actual implementation of the event, the event handler, and the main one.
enum
contains all available events. An abstract event is the basis from which all concrete events originate. An event handler is an abstract template with an event as a class of templates for providing type security. The event bus is responsible for propagating all published events to the appropriate handlers.
enum EVENT_TYPE { ON_EVENT_1, ON_EVENT_2 }; class AbstractEvent { public: AbstractEvent() {}; virtual ~AbstractEvent() {}; virtual EVENT_TYPE type() = 0; }; template<class T> class AbstractEventHandler { public: AbstractEventHandler() {}; virtual ~AbstractEventHandler() {}; virtual void on_event(T *event) = 0; }; class EventBus { public: EventBus() {}; virtual ~EventBus() {}; void subscribe(EVENT_TYPE type, AbstractEventHandler<AbstractEvent> *eventHandler) {
Below is my specific event and event handler, and most importantly ()
class ConcreteEvent : public AbstractEvent { public: ConcreteEvent() {}; virtual ~ConcreteEvent() {}; EVENT_TYPE type() { return ON_EVENT_1; }; }; class ConcreteEventHandler : public AbstractEventHandler<ConcreteEvent> { public: ConcreteEventHandler() {} virtual ~ConcreteEventHandler() {}; void on_event(ConcreteEvent *event) {
The compiler returns an error with the message that to call
no corresponding function
EventBus::subscribe(EVENT_TYPE, ConcreteEventHandler*)
and that the only candidates are
void EventBus::subscribe(EVENT_TYPE, AbstractEventHandler<AbstractEvent>*)
How can I implement the EventBus :: subscribe method to accept specific implementations of my abstract class?
Update: Solution
I changed the description of the EventBus::subscribe
method to the following, and now it works great:
template<typename T> void subscribe(EVENT_TYPE type, AbstractEventHandler<T> *eventHandler) { }
Thanks, Rohan, for your hints! They helped me find this solution.