How can I call a lambda function from another lambda function

Viewed 5901

Consider the contrived class below with a method A() that contains two lambda functions, a1() and a2(). I'd like to be able to invoke a2 from inside a1. However, when I do so, (the second line inside a1), I get the error

Error: variable “cannot be implicitly captured because no default capture mode has been specified”

I don't understand this error message. What am I supposed to be capturing here? I understand that using [this] in the lambda definition gives me access to methods in class foo but I'm unclear as to how to do what I want.

Thanks in advance for setting me straight on this.

class foo
{
   void A()
   {
      auto a2 = [this]() -> int
      {
         return 1;
      };

      auto  a1 = [this]() -> int
         {
            int result;
            result = a2();
            return result;
         };

      int i = a1();
      int j = a2();
   }
};
1 Answers

You need to capture a2 in order to odr-use a2 within the body of a1. Simply capturing this does not capture a2; capturing this only allows you to use the non-static members of the enclosing class. If you expect a2 to be captured by default, you need to specify either = or & as the capture-default.

[this, &a2]  // capture a2 by reference
[this, &]    // capture all odr-used automatic local variables by reference, including a2
Related