0

I have a static method my_method_1() in my_class, and I am trying to use it in a lambda:

static void my_method_1(el);

void my_class::my_method_2()
{
    std::for_each(my_list_.begin(), my_list_.end(),
        [](auto& element)
        {
            my_method_1(element);
        });
}

gcc6 gives me an error:

'this' was not captured for this lambda function

In gcc4, it compiles.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
AlexM
  • 111
  • 4

2 Answers2

0

Cannot reproduce.

According the error ("error: ‘this’ was not captured for this lambda function") my_method_1() isn't static.

If my_method_1() is a non-static method, you can use it inside a lambda capturing this by value (that is like capturing the object by reference); something like

 //  v <- capture by value 
    [=](auto& element)
     { my_method_1(element); }

If my_method_1() is really a static method, please prepare a minimal but complete example to reproduce your problem.

max66
  • 65,235
  • 10
  • 71
  • 111
0

2 observations:

  1. your function is static, you can refer to it as my_class::my_method_1()

  2. You don't need to use a lambda here, have you tried this ?

    void my_class::my_method_2()
    {
        for (auto& element : my_list)
            my_method_1(element);
    }
    
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Michaël Roy
  • 6,338
  • 1
  • 15
  • 19