すでに良い回答があります。以下は単に好奇心ですが、私はそれを使用するように勧めません。
他の人によると答えたように、ラムダfactorial
はそれ自身をキャプチャしようとします。したがって、ステートレスではありません。したがって、関数ポインタへの変換はできません。 (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';
}
を
ラムダは、グローバルまたはstatic
オブジェクトをキャプチャする必要はありませんので、あなたがfactorial
グローバルまたはstatic
変数を作る場合、あなたはそれをキャプチャする必要はありませんし、これが正常に動作します
#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
排除し、さらに:-)を難読化したい場合:
を
また、このような工場を作成することができます3210
// 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;
}
ラムダは何もキャプチャしなければ関数ポインタに変換できます。 – jrok
あなたが正しいですね。知っておいて、ありがとう。 – sircodesalot
これはほぼhttp://stackoverflow.com/questions/2067988/recursive-lambda-functions-in-c0xの複製です。 – doctorlove