Last active
December 29, 2017 15:29
-
-
Save bruceoutdoors/337c8e0ab621e8ecc7e8 to your computer and use it in GitHub Desktop.
Simple implementation of the Signal and Slot (Observer pattern) mechanism.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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