简体   繁体   English

在lambda表达式中调用方法

[英]Call method inside lambda expression

I want to call a method of my class inside a lambda expression: 我想在lambda表达式中调用我的类的方法:

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? 我能怎么做?

You need to capture this , either explicitly or implicitly: 您需要显式或隐式地捕获this

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对象并在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 . 或者,如果你的意思是lambda是在my_class的方法中,那么捕获this Or, if it's a static method then you can call my_class::my_method(obj) without capturing anything, like bames53 said below. 或者,如果它是一个静态方法,那么你可以调用my_class::my_method(obj)而不捕获任何东西,比如下面的bames53。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM