-
-
Save atschwarz/05cefb146ba4125acab96a6301940f3a to your computer and use it in GitHub Desktop.
This file contains 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
#ifndef __DISPATCHER_H | |
#define __DISPATCHER_H | |
#include <functional> | |
#include <list> | |
template <typename... Args> | |
class Dispatcher | |
{ | |
public: | |
typedef std::function<void(Args...)> CBType; | |
class CBID | |
{ | |
public: | |
CBID() : valid(false) {} | |
private: | |
friend class Dispatcher<Args...>; | |
CBID(typename std::list<CBType>::iterator i) | |
: iter(i), valid(true) | |
{} | |
typename std::list<CBType>::iterator iter; | |
bool valid; | |
}; | |
// register to be notified | |
CBID addCB(CBType cb) | |
{ | |
if (cb) | |
{ | |
cbs.push_back(cb); | |
return CBID(--cbs.end()); | |
} | |
return CBID(); | |
} | |
// unregister to be notified | |
void delCB(CBID &id) | |
{ | |
if (id.valid) | |
{ | |
cbs.erase(id.iter); | |
} | |
} | |
void broadcast(Args... args) | |
{ | |
for (auto &cb : cbs) | |
{ | |
cb(args...); | |
} | |
} | |
private: | |
std::list<CBType> cbs; | |
}; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment