2

I am using a std::for_each loop on a local variable of a member function of a class. I would like to call another member function of that same class from the lambda in the for_each. Below is a simplified example of what I'm trying to do:

void some_class::another_function()
{
    cout << "error";
}
void some_class::some_function( function<bool(const int)> &f)
{
    vector<int> local_variable = {0,0,0,1,1,3,5,43};

    std::for_each( local_variable.begin(), local_variable.end(),
            [&f](const int item)
            {
                if( !f(item) )
                    another_function();
            }
}

GCC 4.6 is telling me that this isn't captured (so I should do that). Is that the best solution? Or should I only capture those functions I need (but that could be messy for larger constructs)?

rubenvb
  • 74,642
  • 33
  • 187
  • 332

2 Answers2

5

GCC is right: to call member functions on this from inside a lambda, you must capture this. If the member function does not depend on the data members, make it static, and then you do not need to capture this.

You cannot capture "functions", only local variables (including parameters and this, but not specific data members).

Anthony Williams
  • 66,628
  • 14
  • 133
  • 155
  • In lieu of explicitly capturing `this`, he could just use [&] to capture everything by reference. It's a local function using `std::for_each`; there's no reason not to capture everything by reference and potentially optimize the compiler-generated functor into a simple function pointer. – Nicol Bolas Jun 20 '11 at 17:05
  • Only lambdas that capture **nothing** can be reduced to a function pointer. However, regardless of the capture set, the lambda will be a class with an inline function call operator, and will likely be inlined directly into the `std::for_each` loop. Capturing everything with `[&]` is certainly less typing than explicitly capturing each variable. – Anthony Williams Jun 20 '11 at 20:34
1

You need to capture this if you want to call member functions, and that's pretty much the end of it.

Puppy
  • 144,682
  • 38
  • 256
  • 465