0

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.

3
  • C++ lambdas are function objects, not functions, so casting a lambda to a function pointer is most certainly invoking undefined behavior. Commented Apr 22, 2011 at 0:05
  • Ok, so how to pass a lambda to a function? Commented Apr 22, 2011 at 10:16
  • @user408141 : Make the function a template (so it doesn't know/care what's being passed to it) or have the function take a std::function<> of the appropriate signature. Commented Apr 22, 2011 at 14:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments