You already have good answers. The following is just a curiosity but I wouldn't suggest you to use it.
As said by others answer, the lambda factorial
tries to capture itself and hence it's not stateless. Therefore, it's not convertible to a function pointer.
Lambdas don't need to capture global or static
objects, so if you make factorial
a global or static
variable then you don't need to capture it and this works fine (gcc 4.7.2)
#include <iostream>
typedef int (*function)(int);
int main() {
static function factorial = [](int x){
return (x < 2) ? 1 : x * factorial(x - 1);
};
std::cout << factorial(5) << '\n';
}
You can also create a factory like this:
#include <iostream>
typedef int (*function)(int);
function make_factorial() {
static function factorial = [](int x){
return (x < 2) ? 1 : x * factorial(x - 1);
};
return factorial;
}
int main() {
auto factorial = make_factorial();
std::cout << factorial(5) << '\n';
}
If you want to obfuscate even more :-) then eliminate the typedef
:
// This is a function returning a pointer to a function taking an int and returning an int.
int (*(make_factorial)())(int) {
static int (*factorial)(int) = [](int x){
return (x < 2) ? 1 : x * factorial(x - 1);
};
return factorial;
}