mardi 23 décembre 2014

Use methods as callback in C++ in a convenient way

I want to use methods as callbacks. I know that there is a very generic syntax that allows to use any kind of callable as a callback:



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

getline(cin, string());

return 0;
}


Please note that it must be possible to register methods of any kind of class as callbacks.


However I would like to allow the following more convenient syntax for registering methods:



registrar.registerCallback(&C::m, c); // Method


Is it possible to provide a registerCallback() overload that allows a more basic syntax without the need for using bind when registering a method?


Aucun commentaire:

Enregistrer un commentaire