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)?
GCC is right: to call member functions on
thisfrom inside a lambda, you must capturethis. If the member function does not depend on the data members, make itstatic, and then you do not need to capturethis.You cannot capture “functions”, only local variables (including parameters and
this, but not specific data members).