Skip to content

Instantly share code, notes, and snippets.

@sagi-z
Last active July 4, 2019 20:13
Show Gist options
  • Save sagi-z/f8b734a2240ce203ba5b2977e54b4414 to your computer and use it in GitHub Desktop.
Save sagi-z/f8b734a2240ce203ba5b2977e54b4414 to your computer and use it in GitHub Desktop.
#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