I want to make a library in which a part allows to bind a callback function to some event. The library class has a normal function which is called by the external caller. The function can fire one or more events, to which the caller should be notified using the callback he might have registered with the library class.
To implement that functionality I want to use function pointers. But the compiler keeps on complaining about types.
#include <iostream>
#include <functional>
using std::cout;
using std::endl;
bool checkGT5(int a);
class A
{
private:
std::function<bool(int)> f = nullptr;
public:
void setF(std::function<bool(int)> f) { this->f = f; }
bool call(int a) { if (f) { return f(a); } return false; }
};
bool checkGT5(int a)
{
return a > 5;
}
class B
{
private:
bool checkGT7(int a) { return a > 7; }
A a;
public:
void doStuff()
{
// error: cannot convert 'bool (B::*)(int)' to 'std::function<bool(int)>'
a.setF(&B::checkGT7);
cout << a.call(9) << endl;
}
};
int main()
{
// OK
cout << checkGT5(7) << endl;
// OK
A a;
a.setF(&checkGT5);
cout << a.call(7) << endl;
// error: cannot convert 'bool (B::*)(int)' to 'std::function<bool(int)>'
// would fail even if function was public
a.setF(&B::checkGT7)
return 0;
}
The same happens with 'normal' function pointers like bool (*g)(int)
. I can assign a value just fine. I can also declare it bool (*B::g)(int)
and assign a function from class B. But I don't want to hardcode that only class B can assign a function. Any class should be able to.
How do I do that?
I have tried casting to void*, but it said it can't cast, both using static and c-style casts. What's the proper way to do this?