LoginSignup
8
8

More than 5 years have passed since last update.

lambda の再帰的定義

Last updated at Posted at 2013-12-06

あらゆる処理系で可能かは定かではないが、Visual C++ では lambda を再帰的に定義できる。

#include <iostream>
#include <functional>

int main() {
    // function<> で受けるのがキモ
    std::function<int(int)> factorial =
        [&](int n) { return n == 0 ? 1 : n * factorial(n-1); };
        // ↑ factorialはlambdaの外なので & capture が必要
    std::cout << factorial(5) << std::endl;
}
8
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8