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?
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.
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.
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; };
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.
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 });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With