捕获访问成员函数所需的权限? [英] Capturing this required to access member functions?
问题描述
我在类的成员函数的局部变量上使用 std :: for_each
循环。我想从for_each中的lambda调用同一类的另一个成员函数。以下是我要执行的操作的简化示例:
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告诉我这个
没有被捕获(所以我应该这样做)。那是最好的解决方案吗?或者我应该只捕获我需要的那些功能? (但这对于较大的结构可能会比较混乱)?
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是正确的:在 this
,您必须捕获 this
如果成员函数不依赖于数据成员,则将其设为静态
,然后您无需捕获此
。
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
.
您无法捕获函数,只能捕获局部变量(包括参数和 this
,但不能捕获特定的数据成员)。
You cannot capture "functions", only local variables (including parameters and this
, but not specific data members).
这篇关于捕获访问成员函数所需的权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!