c++ - 如何在 C++ 函数中实现递归函数?

标签 c++ recursion lambda

我了解 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 的类型,因此程序格式错误。

更多引用:

修复: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/

相关文章:

javascript - Javascript "delay evaluation"想要避免急切评估时如何运行?

.net - 递归序列生成

c++ - 如何删除/取消来自 tbb::flow::graph 的消息?

c++ - C2594 : Ambiguous Conversion with COM Object

c++ - Visual Studio 2005 中的默认字符集 'Unicode'

windows - 如何递归更改 WAMP 服务器上的文件夹权限

c# - Lambda 表达式辅助

java - 在不同的类中实现类的方法

python - 如果满足 lambda 条件,则删除整个列表

C++ 在构造函数中使用 this 指针