Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method inside lambda expression

Tags:

c++

c++11

lambda

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?

like image 251
gliderkite Avatar asked Jul 01 '12 17:07

gliderkite


People also ask

Can we call function inside lambda function?

Functions enable encapsulation and code re-use. Most programming languages support the concept of code synchronously calling functions within a code base. In this case, the caller waits until the function returns a response.

How do you call a method in lambda?

Thus, a lambda expression results in a form of anonymous class. In a method reference, you place the object (or class) that contains the method that you want to call before the delimiter :: operator and the name of the method is provided after it without arguments.

How do you call a lambda function in C++?

Lambdas can both capture variables and accept input parameters. A parameter list (lambda declarator in the Standard syntax) is optional and in most aspects resembles the parameter list for a function. auto y = [] (int first, int second) { return first + second; };

Can lambda call another function Python?

Lambda expressions are for when we'd like to define a function and pass it into another function immediately. This is the most appropriate use of lambda expressions: passing a function into another function while defining that passed function all on one line of code.


2 Answers

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     }); 
like image 126
Xeo Avatar answered Sep 30 '22 02:09

Xeo


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.

like image 28
David Avatar answered Sep 30 '22 01:09

David