Skip to content

Instantly share code, notes, and snippets.

@stephanpareigis
Forked from anonymous/Dispatcher.cpp
Created April 25, 2016 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephanpareigis/ee843e45802b5779f12b0d8c73d749c3 to your computer and use it in GitHub Desktop.
Save stephanpareigis/ee843e45802b5779f12b0d8c73d749c3 to your computer and use it in GitHub Desktop.
#include "Dispatcher.h"
#include <utility>
Dispatcher::Dispatcher() noexcept { }
Dispatcher::Dispatcher(std::initializer_list<container_type::value_type> initL)
: cont_{ std::move(initL) } { }
void Dispatcher::registerNotification(Notification notif, value_type const &callable) {
cont_.emplace(notif, callable);
}
void Dispatcher::registerNotification(Notification notif, value_type &&callable) {
cont_.emplace(notif, std::move(callable));
}
void Dispatcher::unregisterNotification(Notification notif) {
auto it = cont_.find(notif);
if (it != std::end(cont_)) {
cont_.erase(it);
}
}
void Dispatcher::callHandler(Notification notif) {
auto it = cont_.find(notif);
if (it != std::end(cont_)) {
it->second();
}
}
#pragma once
#include <functional>
#include <map>
#include <initializer_list>
class Dispatcher final {
public:
using value_type = std::function<void (void)>;
enum class Notification {
one,
two,
three
};
using container_type = std::map<Notification, value_type>;
Dispatcher() noexcept;
Dispatcher(std::initializer_list<container_type::value_type> initL);
void registerNotification(Notification notif, value_type const &callable);
void registerNotification(Notification notif, value_type &&callable);
void unregisterNotification(Notification);
void callHandler(Notification notif);
private:
container_type cont_;
};
int main() {
Dispatcher disp{ { Dispatcher::Notification::one, [] { std::cout << "one\n"; } },
{ Dispatcher::Notification::two, [] { std::cout << "two\n"; } }
};
disp.registerNotification(Dispatcher::Notification::three, [] { std::cout << "three\n"; });
disp.callHandler(Dispatcher::Notification::one);
disp.callHandler(Dispatcher::Notification::two);
disp.callHandler(Dispatcher::Notification::three);
disp.unregisterNotification(Dispatcher::Notification::one);
disp.callHandler(Dispatcher::Notification::one);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment