jeudi 28 mai 2015

How to store method pointers to arbitrary class types in the same list?

I need a way to store a list of method pointers, and the method pointers could belong to classes of different types. So for example:

vector<MethodPointers> list;

class A {
    void function(int, int) { ... }
}

class B {
    void function(int, int) { ... }
}

A a;
B b;
MethodPointer p1(&A::function, &a);
MethodPointer p2(&B::function, &b);

list.push_back(p1);
list.push_back(p2);

What are the c++11 ways to implement this? I have looked at std::bind and got it to work, but it seems like 4 times slower than using a virtual-methods approach, according to my tests. I tried std::mem_fn but could not get it to work. Does anybody know if it can?

The reason I need this is because I have a class which can emit events - and I want arbitrary instances to subscribe to these events as method calls. Is this possible to do?

PS. Conditions apply: 1. I don't want to use Boost 2. I don't want to use a 'Listener' interface, where a subscriber have to subclass an abstract interface class.

Thank you for your time.

Aucun commentaire:

Enregistrer un commentaire