您永远无法知道 lambda 函数的类型,因为逻辑上发生的是编译器生成一个(本地)类,其中函数调用运算符重载,并且词法闭包由该(本地)类的数据成员表示。这就是 lambda 函数在逻辑上发生的情况,例如:
auto foo = [](int x, int y) { return x + y; };
编译器在逻辑上这样做:
struct CompilerGeneratedName { void operator()(int x, int y) const { return x + y; } };
CompilerGeneratedName foo;
由于编译器生成一个(本地)类,它生成一个名称,因此您永远不能显式编写类型,您只能从模板函数参数的类型推导或使用 auto/decltype 推导出类型。
此外,C++0x 闭包是静态分配的,因此无论如何您都不能安全地返回原始 C++0x 闭包。
仍然有几种方法可以实现这一点,第一种更灵活并且支持捕获词法范围的 lambda 函数。使用 std::function,如果你有一个没有从外部范围捕获任何东西的 lambda 函数,那么你可以使用函数指针,但是这种转换更多地用于处理遗留代码而不是任何东西。
所以基本上你想要的是这样的:
std::function< int (int) > foo(int x)
{
return [x](int y)->int{return x * y;};
}
The reason why I kept on saying logically, is because this is how boost::lambda kind of works originally (even though C++03 does not allow local classes to used in template function arguments) and where the idea of adding lambda functions originate from but since this is a language feature now compiler vendors could implement it in different and more efficient ways like when capturing all of the environment by reference the compiler can just pass a pointer to the call stack instead of the logical way while still maintaining the logical view.