recursive template instantiation exceeded maximum depth of 256

前端 未结 3 1737
無奈伤痛
無奈伤痛 2021-01-17 17:27

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:

相关标签:
3条回答
  • 2021-01-17 18:01

    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.

    0 讨论(0)
  • 2021-01-17 18:09

    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));
    }
    
    0 讨论(0)
  • 2021-01-17 18:11

    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;
    }
    
    0 讨论(0)
提交回复
热议问题