我在std::for_each类的成员函数的局部变量上使用循环.我想从for_each中的lambda调用同一个类的另一个成员函数.以下是我正在尝试做的简化示例:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
GCC 4.6告诉我this没有捕获(所以我应该这样做).这是最好的解决方案吗?或者我应该只捕获我需要的那些功能(但对于较大的构造可能会很麻烦)?
GCC是对的:this要从lambda内部调用成员函数,你必须捕获this.如果成员函数不依赖于数据成员,请创建它static,然后您不需要捕获this.
您无法捕获"函数",只能捕获局部变量(包括参数this,而不是特定的数据成员).