Skip to content

Instantly share code, notes, and snippets.

@entwanne
Created February 13, 2013 09:19
Show Gist options
  • Save entwanne/905a0dd4d2675a0780b2 to your computer and use it in GitHub Desktop.
Save entwanne/905a0dd4d2675a0780b2 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <map>
#include <list>
class Object
{
public:
struct s_slot
{
Object* o;
void (Object::*slot)();
};
protected:
static std::map< std::string, std::list< s_slot > > _slots;
public:
void connect(const std::string& s, void (Object::*slot_f)())
{
s_slot slot;
slot.o = this;
slot.slot = slot_f;
_slots[s].push_back(slot);
}
template < typename T1, typename T2 >
void emit(const std::string& s, T1 t1, T2 t2)
{
std::map< std::string, std::list< s_slot > >::const_iterator itm;
itm = _slots.find(s);
if (itm != _slots.end())
{
std::list< s_slot >::const_iterator it;
for (it = itm->second.begin(); it != itm->second.end(); ++it)
{
((it->o)->*reinterpret_cast< void (Object::*)(T1, T2) >(it->slot))(t1, t2);
}
}
}
};
std::map< std::string, std::list< Object::s_slot > > Object::_slots;
class Object2 : public Object
{
public:
Object2(int c) : _c(c) {}
void tata(int a, int b)
{
std::cout << a + b + _c << std::endl;
}
protected:
int _c;
};
class Object3 : public Object
{
public:
void tutu(int a, int b)
{
std::cout << a - b << std::endl;
}
};
int main()
{
Object2 o(4);
Object3 p;
o.connect("toto", reinterpret_cast< void (Object::*)() >(&Object2::tata));
p.connect("toto", reinterpret_cast< void (Object::*)() >(&Object3::tutu));
p.emit("toto", 42, 21);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment