我的代码在另一个函数中包含函数,如下所示:
ReturnType OuterFunction(someParameters, MyType* mt)
{
function<OtherType*(parameterList)> innerFunction =
[this](parameterList)
{
return someOtherFunction(someParameters, mt);
}
}
我在
MyType
中添加了一个参数someOtherFunction
,并修改了它的调用,如上面的代码所示。mt
是从OuterFunction
传递的变量,我无法在someOtherFunction
中使用它。这给我一个错误
An enclosing-function local variable cannot be referenced in a lambda body unless if it is in the capture list.
最佳答案
您必须在尝试使用的lambda中将mt
添加到捕获列表中。
默认情况下,您无权访问外部变量。并且添加this
会为您的对象添加一个Pointer。
ReturnType OuterFunction(T s1, K s2, MyType* mt)
{
function<OtherType*(parameterList)> innerFunction =
[s1,s2,mt](parameterList)
{
return someOtherFunction(s1, s2, mt);
}
}
你可以看看这个https://docs.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=vs-2019
关于c++ - 从内部函数内部使用外部函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61315708/