【发布时间】:2012-02-04 07:15:55
【问题描述】:
我正在阅读对"Printing 1 to 1000 without loop or conditionals" 的回复,我想知道为什么有必要在最佳答案中包含 NumberGeneration 的特殊情况。
如果我删除它并在模板中添加对 N == 1 的检查(下面的代码),代码编译失败,并显示“模板实例化深度超过最大值”,但我不知道为什么。条件在编译时的处理方式不同吗?
#include <iostream>
template<int N>
struct NumberGeneration
{
static void out(std::ostream& os)
{
if (N == 1)
{
os << 1 << std::endl;
}
else
{
NumberGeneration<N-1>::out(os);
os << N << std::endl;
}
}
};
int main()
{
NumberGeneration<1000>::out(std::cout);
}
【问题讨论】:
标签: c++ compile-time