开发者

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::me开发者_JAVA技巧mberFunc() {
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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜