使用内部函数内部的外部函数变量

时间:2020-04-20 05:32:33

标签: c++

我的代码在另一个函数中包含函数,如下所示:

ReturnType OuterFunction(someParameters, MyType* mt)
{
   function<OtherType*(parameterList)> innerFunction = 
   [this](parameterList)
   {
      return someOtherFunction(someParameters, mt);
   }
}

我已向MyType添加了一个参数someOtherFunction并修改了它的调用,如上面的代码所示。

mt是从OuterFunction传递过来的变量,我无法在someOtherFunction中使用它。

这给我一个错误

除非在捕获列表中,否则不能在lambda主体中引用封闭函数局部变量。

1 个答案:

答案 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