jeudi 12 septembre 2019

Using std::bind and std::function to use a class member function as callback for another class member routine

This may have been explored before, but I am not certain how it works out, and how t should in my particular case..

Essentially I have a class, with a callback defined as :

class Foo
{
    public:
    using someCallbackName = std::function<void(int)>;
    void someFunc();
    Foo(int, someCallBackName);
    private : 
    someCallbackName m_callBack;
}

void Foo::someFunc()
{
    m_callBack(1);
}

I used to call this in main() or by just referencing function of similar signature..

void someOtherFunction(int x)
{
    cout << x;
}

int main()
{
    Foo::someCallbackName callBack = someOtherFunction;
    Foo foo(5, callBack);
}

I decided though, that I may need someOtherFunction as a class member, and put it as part of a class. However, using class member function someOtherFunction as a callback required making it static, which worked fine, but which would mean it wouldn't have access to non-static class members, which sort of defeated the purpose to put it in a class.

I tried using : C++ callback using class member

and the struct access as given in : https://en.cppreference.com/w/cpp/utility/functional/bind

..but it does not seem to work, the std::bind to

Foo::someCallbackName callBack = std::bind(not_sure_what_to_use_here);

keeps giving errors saying no suitable conversion, which makes me think that somewhere the signature of callback or mechanism of using std::bind in the code is erroneous.

Keeping class Foo as is, how can m_callBack call someOtherFunction ?

Aucun commentaire:

Enregistrer un commentaire