Reputation: 1276
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.
Upvotes: 0
Views: 84
Reputation: 218268
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();
}
Upvotes: 1