mardi 23 décembre 2014

Alterantive for callbacks using std::function

Currently I am trying out a code that does essentially the following:



void f(int x) { cout << "f("<<x<<")" << endl; }

class C
{
public:
void m(int x) { cout << "C::m("<<x<<")" << endl; }
};

class C2
{
public:
void registerCallback(function<void(int)> f)
{
v.push_back(f);
}

private:
vector<function<void(int)>> v;

void callThem()
{
for (int i=0; i<v.size(); i++)
{
v[i](i);
}
}
};

int main()
{
C2 registrar;

C c;
registrar.registerCallback(&f); // Static function
registrar.registerCallback(bind(&C::m, &c, placeholders::_1)); // Method

return 0;
}


This works pretty well. However I got stuck with this pattern. I would like to check if a callback already has been registered and I would like to be able to unregister a callback by removing it from the vector. I just learned that std::function objects can not be compared which means it is impossible to search for their existence in the container.


So I need an alternative. Of course I would like to keep compile-time type checks and the ability to register methods of arbitrary classes.


How can I achieve a similar solution that allows unregistering the callback and checking for double registration? Are there any trade-offs I need to accept?


Aucun commentaire:

Enregistrer un commentaire