0

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?

FalcoGer
  • 2,278
  • 1
  • 12
  • 34
  • The function B::checkGT7() isnt static. – DS_London Jan 30 '21 at 09:05
  • @DS_London what's your point? I don't want the function needing to be static. – FalcoGer Jan 30 '21 at 09:07
  • @FalcoGer In your main() function there is no instance of B. A non-static member function receives an implicit ‘this’ pointer when called: that can’t happen if you haven’t created an instance. Ask yourself what would happen in checkGT7() if that function wanted to access the B::a member variable? – DS_London Jan 30 '21 at 09:17

0 Answers0