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.
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);
}
Code generation and compilation doesn’t branch depending on conditionals! Consider this:
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: