c++ - 从内部函数内部使用外部函数中的变量

标签 c++

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

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/

相关文章:

c++ - 还在获取重复值?

c++ - 如何在 Debug模式下使用 Netbeans 编译 Assimp?

c++ - 是否有一种自动合并 C++ 实现(.cpp)和头文件(.h)文件的方法

c# - 是否有与 boost::interprocess::basic_string 等效的 C#?

c++ - 在处理浮点值时,我应该结合乘法和除法步骤吗?

c++ - 代码不会在 g++ 中编译,而在 clang++ 中会编译

c++ - CUDA 和复制构造函数

c++ - boost 正则表达式捕获组

c++ - 用于提高中间浮点计算精度的编译器标志

c++ - 类成员在其他类中充当友元 C++