Call method inside lambda expression

23,400

Solution 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
    });

Solution 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.

Share:
23,400

Related videos on Youtube

gliderkite
Author by

gliderkite

Updated on July 09, 2022

Comments

  • gliderkite
    gliderkite almost 2 years

    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?

    • bames53
      bames53 almost 12 years
      details are needed. Where is the for_each code, in another member function of my_class? Is my_method a static or non-static function? If it's not static and for_each is being not in a my_class member function, then what instance do you want to be calling the my_method on? Does it matter?
    • gliderkite
      gliderkite almost 12 years
      The for_each is inside another non-static member function of my_class. Why downvote?
    • bames53
      bames53 almost 12 years
      because the question isn't clear as written.
  • bames53
    bames53 almost 12 years
    assuming that the lambda is being used from a member function of my_class. The question's not specific enough to tell if this is the case.
  • bames53
    bames53 almost 12 years
    and if it is a static method then you can call it without an instance: [](my_obj &obj) { my_class::my_method(obj); }. The question's not specific enough for us to know if it's static or not.
  • Xeo
    Xeo almost 12 years
    @bames: I think it is, the comment inside the lambda indicate that it should be called as my_method(o), but I can see where you're coming from.
  • RandomGuy
    RandomGuy about 6 years
    @Xeo You can use an alias to avoid to "pollute" all the scope with the this variables like this: [self = this], then inside the lambda you need to refer explicitly to the this variables / functions that you want to access like: self->my_method(o);, I believe this is a safer way to capture the this, since you always need to be explicit for the accesses.