recursive template instantiation exceeded maximum depth of 256

前端 未结 3 1741
無奈伤痛
無奈伤痛 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:09

    You need a stopping state like the following:

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

    since f2() 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));
    }
    

提交回复
热议问题