Skip to content

Instantly share code, notes, and snippets.

@bruceoutdoors
Last active December 29, 2017 15:29
Show Gist options
  • Save bruceoutdoors/337c8e0ab621e8ecc7e8 to your computer and use it in GitHub Desktop.
Save bruceoutdoors/337c8e0ab621e8ecc7e8 to your computer and use it in GitHub Desktop.
Simple implementation of the Signal and Slot (Observer pattern) mechanism.
/**
* Signal.hpp
* - Simple implementation of the Signal and Slot (Observer pattern) mechanism.
* Requires C++11 compatible compiler.
*
* @author Lee Zhen Yong
*/
#pragma once
#include <functional>
#include <map>
template<class... Args>
class Signal
{
public:
// connect to slot; returns function that disconnects this link
std::function<void()> connect(std::function<void(Args... args)> func)
{
int funcKey = m_key;
m_funcs[m_key++] = func;
return [=]() {
m_funcs.erase(funcKey);
};
}
void broadcast(Args... args)
{
for (auto &func : m_funcs) {
func.second(args...);
}
}
void disconnectAll()
{
m_funcs.clear();
}
private:
int m_key = 0;
std::map<int, std::function<void(Args...)> > m_funcs;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment