jeudi 2 avril 2015

C++11 Observers Pass parameters on Notify

I'm coming from C# and trying to implement a simple Events/EventHandler pattern in c++11 which i believe the common name is Observers and signals, i know there are boost library and others but i dont want to use any external libs, however, while searching online i found a simple implementation for what i need, so i took and modified the code and it works ok, now my problem is the parameters are passed when registering events/observers and not when raising/signaling/notifying which i find it a bit awkward, anyway, can anyone help me to extend the following code by adding the functionality to accept parameters when raising the event as well ?



class EventManager
{
private:

static std::map<EventType, std::vector<std::function<void()>>> _eventHandlers;

public:
EventManager() = default;


template <typename EventHandler>
static void RegisterEventHandler(EventType&& eventType, EventHandler&& eventHandler)
{
EventManager::_eventHandlers[std::move(eventType)].push_back(std::forward<EventHandler>(eventHandler));
}

static void Raise(const EventType& event)
{
for (const auto& eventHandler : EventManager::_eventHandlers.at(event))
{

eventHandler();
}
}

// disallow copying and assigning
EventManager(const EventManager&) = delete;
EventManager& operator=(const EventManager&) = delete;


};

Aucun commentaire:

Enregistrer un commentaire