user408141
user408141

Reputation:

Callback parameter for lambdas and member functions

I have this function:

void func(boost::function<void(float)> cb){
//do something with cb()
}

It works with lambdas and functions. But it does not allow me to pass a member function or a lambda defined in a member function.

I tried to cast something like this:

void class::memberFunc() {
void func((void(*)(float))([](float m){}));
}

But it seems like lambda is ignored at calls. And no idea how to pass a member function too.

Upvotes: 0

Views: 126

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

Given:

struct T {
   T(int x) : x(x) {};
   void foo() {
      std::cout << x;
   }

   int x;
};

The object pointer is an implicit first parameter to functions, and this becomes explicit when dealing with boost::function.

You can "hide" it from func by binding it early:

void func(boost::function<void()> cb) {
   cb();
}

int main() {
   T t(42);
   func(boost::bind(&T::foo, &t));
}

Or otherwise you can bind it late:

T t(42);

void func(boost::function<void(T*)> cb) {
   cb(&t);
}

int main() {
   func(boost::bind(&T::foo, _1));
}

See it working here.

Upvotes: 1

Related Questions