recursive template instantiation exceeded maximum depth of 256

别等时光非礼了梦想. 提交于 2019-12-23 07:37:01

问题


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:

recursive template instantiation exceeded maximum depth of 256

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
}

回答1:


You need a stopping state like the following:

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

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

template <> struct Factorial<0>

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));
}



回答2:


When N == 0, the compiler still has to instantiate f2<-1> because the function call is present in the code. When f<-1> is instantiated, f<-2> is instantiated and so on. Applying this statement again and again, the compiler will keep recursing through the template until it exceeds the max depth.




回答3:


You need to define a specialization of the template function to stop the recursion at the compile time rather than runtime, just as your struct version did.

template <int N>
int f2()
{
    return N * f2<N - 1>();
}

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


来源:https://stackoverflow.com/questions/22800245/recursive-template-instantiation-exceeded-maximum-depth-of-256

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!