我的代码在另一个函数中包含函数,如下所示:
ReturnType OuterFunction(someParameters, MyType* mt)
{
function<OtherType*(parameterList)> innerFunction =
[this](parameterList)
{
return someOtherFunction(someParameters, mt);
}
}
我已向MyType
添加了一个参数someOtherFunction
并修改了它的调用,如上面的代码所示。
mt
是从OuterFunction
传递过来的变量,我无法在someOtherFunction
中使用它。
这给我一个错误
除非在捕获列表中,否则不能在lambda主体中引用封闭函数局部变量。
答案 0 :(得分:1)
您必须将mt
添加到您要在其中使用的lambda的捕获列表中。
默认情况下,您无权访问外部变量。并且添加this
就是向您的对象添加一个指针。
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