0

I have a class A that has a function pointer for a callback. The default values are some function pointer from class A but I want to assign a function pointer from class B. I tried std::function and std::bind but it is not working. I tried to use this answer but without success.

The code is:

#include <iostream>
#include <string>
#include <functional>

class A{
public:
    typedef void(*action)() ;

    A( std::function<void()> a  = nullptr)
    {
        if(a)
            m_Func = a; 
        else
            m_Func = std::bind( (this->*(this->dummyFunction))() );
    }
    std::function<void(void)> m_Func;
    void dummyFunction(void){std::cout<<"dummy function\n" <<std::endl;}
};

class B{
public:
    std::function<void()> m_Bfunc(){ std::cout << "class B func\n" <<std::endl;}
};

int main()
{
  B b;
  A a(b.m_Bfunc);
  a.m_Func();
}

I want that the function m_Bfunc to run.

2
  • action is ultimately pointless in this code; get rid of it. Just saying, and it appears you want the bind to be (a) correct (which it isn't) and (b) done from main (which given this layout is the only sane place to wire up b with B:m_BFunc). Commented Jan 2, 2020 at 16:50
  • std::function<void()> m_Bfunc(){ std::cout << "class B func\n" <<std::endl;} declares a functions named m_Bfunc that returns a std::function<void()>, since the function does not return that you're into the realm of undefined behavior. Commented Jan 2, 2020 at 16:53

1 Answer 1

1

It seems you want:

class A{
public:
    A(std::function<void()> a = nullptr)
    {
        if(a)
            m_Func = a; 
        else
            m_Func = [this](){ dummyFunction(); };
    }
    std::function<void()> m_Func;
    void dummyFunction(){std::cout<<"dummy function\n" <<std::endl;}
};

class B{
public:
    void func(){ std::cout << "class B func\n" <<std::endl;}
};

int main()
{
  B b;
  A a([&](){b.func(); });
  a.m_Func();
}

Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.