Returning a lambda function in C++

Viewed 900
typedef int (*identity_t)(int); 
identity_t retFun() { 
  return [](int x) { return x; };
}

This piece of code works, but why do I need the first line?

Why doesn't the code below work?

int (*)(int) retFun() { 
  return [](int x) { return x; };
}
2 Answers

The typedef makes it easier to write the function declaration, but you don't need the typedef if you know the right syntax:

int (*retFun())(int) {
    return [](int x) { return x; };
}

As you can see, the typedef not only makes it easier to write; it makes it easier to read as well.

C++ syntax inherited from C is weird, counterintuitive and archaic. You need the typefef to cope with the fact.

int (*retFun())(int) { ... } 

is frankly an unreadable mess.

The new crop of the C++ syntax alleviates the problem somewhat.

auto retFun () -> auto (*)(int) -> int { 
   return [](int x) { return x; };
}

The new syntax is written mostly left-to-right, as one would read it.

  auto retFun

"retFun is ..."

  () ->

"... a function that takes no arguments and returns ..."

  auto (*)

"... a pointer to ..."

  (int) -> 

"... a function that takes an int argument and returns ..."

  int

"... an int".

More about function declarations.

Related