【发布时间】:2014-05-13 01:47:37
【问题描述】:
我试图使用 constexpr 函数重写 Factorial 实现,但由于某种原因,我不知道为什么会出现编译错误:
递归模板实例化超过最大深度 256
实际上我知道错误消息的含义,但我不知道为什么我会收到此错误以及为什么使用 struct 的代码 1 工作但第二个 using 函数不起作用。它们有什么区别?
// 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
}
【问题讨论】:
-
你为什么在模板中使用 constexpr?为什么不直接传入 N 作为参数呢?为这种事情摆脱 f 模板是我们拥有 constexpr iirc 的原因之一。
-
@KitsuneYMG 同意这是我在回答中指出的
-
@KitsuneYMG:因为对于我正在编写的函数,我需要告诉编译器参数是常量,
const或constexpr都不是(我需要的方式)所以我需要使用模板参数代替。类似于 Nawaz 的回答:stackoverflow.com/questions/9789913/…
标签: c++ templates c++11 recursion clang