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.
actionis ultimately pointless in this code; get rid of it. Just saying, and it appears you want thebindto be (a) correct (which it isn't) and (b) done frommain(which given this layout is the only sane place to wire upbwithB:m_BFunc).std::function<void()> m_Bfunc(){ std::cout << "class B func\n" <<std::endl;}declares a functions namedm_Bfuncthat returns astd::function<void()>, since the function does not return that you're into the realm of undefined behavior.