1

Is there any general way to refer to the current function being executed? Something that would let me do this for example,

([] (int n) -> int {
  if (n <= 1) {
    return 1;
  }

  return n * thisFunc(n - 1);
})()

Mainly, I'm thinking of anonymous functions calling themselves without the use of auxiliary named functions. So avoiding this.

Community
  • 1
  • 1

1 Answers1

0

You can use a function pointer, or function object in C++11, but there is no built-in way to refer to a function. For example:

std::function<int (int)> myFun = [] (int i) 
{
   if i <= 1
   {
       return 1;
   }
   return i * myFun(i-1);
}

I would argue that calling a lambda recursively is not how they were meant to be used. Lambdas are essentially meant to provide inline functionality and thus are meant to be fairly simple. Not to mention that the example you give can very easily be replaced with a loop thus resulting in much more efficient implementation:

int result = 1;
while (i > 1)
{
   result = result * i;
   i--;
}
ventsyv
  • 3,316
  • 3
  • 27
  • 49
  • You're probably right about them not being meant to be called recursively. I was thinking of JavaScript and remembered some similar mechanism that allowed you to refer to the current function. –  Dec 02 '14 at 20:07
  • I actually meant to put the emphasis on not having overly complex lambdas, recursion is not necessarily complex in itself (although it could be). – ventsyv Dec 02 '14 at 20:11