fib 函数与模板有什么区别?

what's the difference about fib function with template?

这是我的代码:

template<int x>
struct factorial
{
    enum :unsigned long long{ value = x * factorial<x - 1>::value };
};

template<>
struct factorial<1>
{
    enum :unsigned long long{ value = 1 };
};

有什么区别

struct factorial<1>
{
    enum :unsigned long long{ value = 1 };
};

struct factorial<0>
{
    enum :unsigned long long{ value = 1 };
};

如果我把0换成1有什么不同? 我在我的机器和 cppinsight 上尝试了它们,没有区别并且工作找到了,但是 cw 说:

fatal error: recursive template instantiation exceeded maximum depth of 1024
    enum :unsigned long long{ value = x * factorial<x - 1>::value };
                                          ^
main.cpp:8:43: note: in instantiation of template class 'factorial<-1024>' requested here
main.cpp:8:43: note: in instantiation of template class 'factorial<-1023>' requested here
main.cpp:8:43: note: in instantiation of...

问题出自这里:https://www.codewars.com/kata/5a74a94f5084d72c710000de/discuss

如果您不为 factorial<0> 提供专门化,它将采用主模板的定义,因此要实例化 factorial<0>;你必须计算:

0 * factorial<0 - 1>::value;

还必须计算 factorial<-1>::value,所以 factorial<-2>::value 等等...

一旦发生在 factorial<-1024>,就达到了编译器的递归限制,它会因给定错误而停止。