如何创建lambda的"引用"?

sir*_*lot 5 c++ lambda c++11

我想捕捉一个"参考"的拉姆达,我认为,一个函数指针会做的伎俩,如:

int (*factorial)(int) = [&](int x){
    return (x < 2)
        ? 1
        : x * factorial(x - 1);
};
Run Code Online (Sandbox Code Playgroud)

但我明白了cannot convert from main::lambda<......> to int(_cdecl *)(int).

那么指向lambda的正确方法是什么?

Pra*_*ian 6

由于lambda不是无状态的,因此无法将其转换为函数指针.请std::function改用.

std::function<int(int)> factorial  = [&](int x){
  return (x < 2)
      ? 1
      : x * factorial(x - 1);
};
Run Code Online (Sandbox Code Playgroud)


Vau*_*ato 5

这将与您已经拥有的最接近:

std::function<int (int)> factorial = [&](int x){
    return (x < 2)
        ? 1
        : x * factorial(x - 1);
};
Run Code Online (Sandbox Code Playgroud)

通常你也可以使用auto,但在这种情况下,它不起作用,因为该函数是递归的.


Cas*_*eri 5

你已经有了很好的答案.以下只是一个好奇心,但我不建议你使用它.

正如其他人所说,lambda factorial试图捕捉自己,因此它不是无国籍的.因此,它不能转换为函数指针.

Lambdas不需要捕获全局或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';
    }
Run Code Online (Sandbox Code Playgroud)

您还可以创建这样的工厂:

    #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';
    }
Run Code Online (Sandbox Code Playgroud)

如果你想更混淆:-)然后消除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;
    }
Run Code Online (Sandbox Code Playgroud)