I am working on c++ 11.
I want to write a function funA in a class, which binds another function funB within the same class. And funB function is a parameter in the function funA. What could be the syntax of the funcA ? I tried using std::function func, but i am not able to compile. Please explain.
Thanks.
class ServiceClass
{
typedef std::function<void(const int&, const int&)> ServiceCallBack;
public:
void ServiceFunc(ServiceCallBack callback)
{
callback(1,2);
}
};
class MyClass
{
public:
ServiceClass serviceClass;
void myFunction(int i)
{
cout << __FUNCTION__ << endl;
cout << i << endl;
}
void myFunction2(int i)
{
cout << __FUNCTION__ << endl << i << endl;
}
void bindFunction(std::function<void()> func)
{
std::bind(func, this, std::placeholders::_1);
func();
}
void testmyFunction()
{
serviceClass.ServiceFunc( std::bind(
MyClass::myFunction,
this,
std::placeholders::_1
));
}
void testmyFunction2()
{
serviceClass.ServiceFunc( std::bind(
MyClass::myFunction2,
this,
std::placeholders::_1
));
}
void testFunctions( int i )
{
if( i == 1 )
{
serviceClass.ServiceFunc( std::bind( MyClass::myFunction, this, std::placeholders::_1 ));
}
else if( i == 2 )
{
serviceClass.ServiceFunc( std::bind( MyClass::myFunction2, this, std::placeholders::_1 ));
}
}
};
Based on some condition, in the function testFunctions, i want to call any of the callback functions, myFunction or myFunction2. So if a can modify the testFunctions to receive a parameter which can take any of the callback functions, then I dont have to write the if else conditions.
Please suggest.