我了解 lambda 函数的工作原理。问题在于,程序在编译器推断出“auto”应该是什么之前调用了函数 recursiveFunction()。问题是,它是一个递归函数,因此函数本身位于定义中。
#include <iostream>
using namespace std;
template <class T>
class Class {
public:
int foo(int x);
};
template <class T>
int Class<T>::foo(int x) {
auto recursiveFunction = [=](int n)->int {
if (n <= 1) return 1;
else return n*recursiveFunction(n-1);
};
return recursiveFunction(x);
}
int main() {
Class<int> c;
cout << c.foo(5) << endl;
return 0;
}
我还使用使用模板的类来实现这一点,以防影响问题。
错误消息如下:
main.cpp: In instantiation of 'int Class<T>::foo(int) [with T = int]':
main.cpp:21:20: required from here
main.cpp:14:40: error: use of 'recursiveFunction' before deduction of 'auto'
else return n*recursiveFunction(n-1);
谢谢!
最佳答案
已回复 here :
The second snippet runs into [dcl.spec.auto]/10:
If the type of an entity with an undeduced placeholder type is needed to determine the type of an expression, the program is ill-formed.
需要 foo 的类型来确定 lambda 体内表达式 foo 的类型,但此时您还没有推导出 foo 的类型,因此程序格式错误。
block 引用>更多引用:
- lambda capture during initialization should be an error
- "a variable declared with an auto specifier cannot appear in its own initializer"
修复:https://godbolt.org/z/np3ULe
#include <iostream> #include <functional> template <class T> class Class { public: int foo(int x); }; template <class T> int Class<T>::foo(int x) { std::function<int(int)> fac = [&fac](int n) -> int { if (n <= 1) return 1; else return n * fac(n - 1); }; return fac(x); } int main() { Class<int> c; std::cout << c.foo(5) << std::endl; return 0; }
关于c++ - 如何在 C++ 函数中实现递归函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58194176/