递归模板实例化超出最大深度256 [英] recursive template instantiation exceeded maximum depth of 256

查看:93
本文介绍了递归模板实例化超出最大深度256的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 constexpr 函数重写阶乘实现,但由于某些原因,我不知道为什么会出现编译错误:

I was trying to rewrite the Factorial implementation using constexpr function but for some reason I have no idea why I get a compile error:


递归模板实例化超过了最大深度256

recursive template instantiation exceeded maximum depth of 256

实际上我知道错误消息的意思是,但我不知道为什么收到此错误,以及为什么使用 struct 的代码1可以工作,而第二个using函数却不能。它们之间有什么区别?

Actually I know what the error message means but what I don't is why I'm getting this error and why the code 1 using struct work but the second using function doesn't. What's the difference between them?

 // yes, I know it doesn't return the factorial value. First I want to make it compile
template <int N>
constexpr int f2()
{
    return N == 0 ? 1 : f2<N - 1>();
}

template <int N> struct Factorial
{
    enum 
    {
        value = N * Factorial<N - 1>::value
    };
};

template <> struct Factorial<0>
{
    enum
    {
        value = 1
    };
};


int main() 
{
    x = f2<4>(); // compile error
    n = Factorial<4>::value; // works fine
}


推荐答案

您需要停止状态,如下所示:

You need a stopping state like the following:

template <>
int f2<0>()
{
   return 0;
}

因为 f2< N -1>()必须实例化,在这种情况下,您的停止状态如下:

since f2<N - 1>() has to be instantiated, you have your stopping state in your other case here:

template <> struct Factorial<0>

但是如果您使用的是 constexpr 真的根本不需要使用模板,因为整个要点是它将在编译时完成,因此将其转换为:

But if you are using constexpr you don't really need to use templates at all since the whole point is that it will be done at compile time, so turn it into this:

constexpr int f2(int n)
{
  return n == 0 ? 1 : (n * f2(n-1));
}

这篇关于递归模板实例化超出最大深度256的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆