Capturing this required to access member functions

2019-07-14 18:21发布

问题:

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)?

回答1:

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).



回答2:

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



标签: lambda c++11