编译时间递归和条件 [英] Compile time recursion and conditionals
问题描述
我正在阅读对打印1到1000无回路或条件,我想知道为什么有必要在NumberGeneration< 1>的特殊情况在顶部的答案。
I was reading the responses to "Printing 1 to 1000 without loop or conditionals" and I am wondering why it is necessary to have the special case for NumberGeneration<1> in the top answer.
如果我删除,添加一个检查N == 1在模板(代码下面),代码失败编译与模板实例化深度超过最大,但我不知道为什么。是在编译时处理不同的条件?
If I remove that and add a check for N == 1 in the template (code below), the code fails compilation with "template instantiation depth exceeds maximum" but I'm not sure why. Are conditionals handled differently in compile-time?
#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);
}
推荐答案
代码生成和编译t分支取决于条件!考虑这个:
Code generation and compilation doesn't branch depending on conditionals! Consider this:
// don't declare bar()!
void foo()
{
if (false) { bar(); }
}
如果您从未声明 bar code>,这是一个编译错误,即使内部作用域永远无法达到。出于同样的原因,不管是否可以到达该分支,
NumberGeneration< N-1>
总是实例化,并且你有无限递归。
If you never declare bar()
, this is a compilation error even though the inner scope can never be reached. For the same reason, NumberGeneration<N-1>
is always instantiated, no matter whether that branch can be reached or not, and you have infinite recursion.
事实上,条件语句的静态模拟正是模板特化:
Indeed, the static analogue of conditionals is precisely template specialization:
template <> struct NumberGeneration<0> { /* no more recursion here */ };
这篇关于编译时间递归和条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!