Call method inside lambda expression

2019-04-18 22:52发布

问题:

I want to call a method of my class inside a lambda expression:

void my_class::my_method(my_obj& obj)
{
}


void my_class::test_lambda()
{ 
   std::list<my_obj> my_list;

   std::for_each(my_list.begin(), my_list.end(), [](my_obj& obj)
   {
      // Here I want to call my_method:
      // my_method(obj);
   });
}

How can I do?

回答1:

You need to capture this, either explicitly or implicitly:

std::for_each(l.begin(), l.end(),
    [this](my_obj& o){ // or [=] or [&]
      my_method(o); // can be called as if the lambda was a member
    });


回答2:

You can't call a non-static method without an object to call it on.

Make a my_class object and capture a reference to it in the lambda...

my_class x;

std::for_each(my_list.begin(), my_list.end(), [&x](my_obj& obj)
//                                            ^^^^
{
    // Here I want to call my_method:
    x.my_method(obj);
});

Or, if you meant the lambda was in a method of my_class then capture this. Or, if it's a static method then you can call my_class::my_method(obj) without capturing anything, like bames53 said below.



标签: c++ lambda c++11