I found a code here Printing 1 to 1000 without loop or conditionals
Can someone please explain how compile time recursion works, couldn\'t find it in google
It repeatedly instantiates the f1
template with decreasing values for N
(f1
calls f1
and so on). The explicit specialization for N==1
ends the recursion: as soon as N
becomes 1, the compiler will pick the specialized function rather than the templated one.
f1<1000>()
causes the compiler to instantiate f1
999 times (not counting in the final call to f1<1>
). This is the reason why it can take a while to compile code that makes heavy use of template meta-programming techniques.
The whole thing relies heavily on the compiler's optimization skills - ideally, it should remove the recursion (which only serves as hack to emulate a for
loop using templates) completely.