简体   繁体   中英

How to pass a parameter to std::bind from a function

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.

typedef void(MyClass::*MY_CLASS_PTR)(int);
// function which takes function pointer as parameter
void testFunctions( MY_CLASS_PTR fptr)
{
// fptr should have which function to bind 
  serviceClass.ServiceFunc( std::bind( fptr , this, std::placeholders::_1 ));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM