Here is my very first event dispatcher. I would like to get both, style and code review, as well as some ideas to improve this implementation (new features etc.)
I tried to write code in C++17 style as much as possible.
IEventDispatcher.h
#pragma once
#include <map>
#include <functional>
template<typename EventType>
class IEventDispatcher
{
public:
using EventHandler = std::function<void()>;
virtual void addEventListener(EventType eventToAdd, EventHandler handler) = 0;
virtual void removeEventListener(EventType eventToRemove) = 0;
virtual void dispatch(EventType eventToDispatch) = 0;
};
EventDispatcher.hpp
#pragma once
#include "IEventDispatcher.h"
template<typename EventType>
class EventDispatcher : public IEventDispatcher<EventType>
{
public:
using EventHandler = std::function<void()>;
EventDispatcher();
~EventDispatcher();
void addEventListener(EventType eventToAdd, EventHandler handler);
void removeEventListener(EventType eventToRemove);
void dispatch(EventType eventToDispatch);
private:
std::multimap<EventType, EventHandler> eventListeners;
};
template<typename EventType>
EventDispatcher<EventType>::EventDispatcher()
{}
template<typename EventType>
EventDispatcher<EventType>::~EventDispatcher()
{}
template<typename EventType>
void EventDispatcher<EventType>::addEventListener(EventType eventToAdd, EventHandler handler)
{
eventListeners.emplace(eventToAdd, handler);
}
template<typename EventType>
void EventDispatcher<EventType>::removeEventListener(EventType eventToRemove)
{
eventListeners.erase(eventToRemove);
}
template<typename EventType>
void EventDispatcher<EventType>::dispatch(EventType eventToDispatch)
{
for (const auto &[event, handler] : eventListeners)
{
if (event == eventToDispatch)
{
handler();
}
}
}