あなたはすでに良い答えを持っています。以下は単なる好奇心ですが、使用することはお勧めしません。
他の人が答えたように、ラムダfactorial
はそれ自体をキャプチャしようとするため、ステートレスではありません。したがって、関数ポインターに変換することはできません。
ラムダはグローバルまたはstatic
オブジェクトをキャプチャする必要がないためfactorial
、グローバルまたはstatic
変数を作成する場合、それをキャプチャする必要はなく、これは正常に機能します (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';
}
次のようなファクトリを作成することもできます。
#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';
}
さらに難読化したい場合は:-)、次を削除し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;
}