Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How compile time recursion works?

Tags:

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

// compile time recursion
template<int N> void f1()
{ 
    f1<N-1>(); 
    cout << N << '\n'; 
}

template<> void f1<1>() 
{ 
    cout << 1 << '\n'; 
}


int main()
{
    f1<1000>();
}

Thank you!

like image 207
VextoR Avatar asked Mar 11 '11 14:03

VextoR


People also ask

How are recursive functions compiled?

It's entirely compiler-dependent ... but most compilers in most languages implement recursion by using the stack. The compiler generates the code that pushes the program arguments, saves the current stack and frame pointers, then simply calls the same function (with the newly updated stack).

Is template a compile time mechanism?

Templates are the feature that supports generic programming in C++, which are compile time mechanism and there is no runtime overhead associated with using them.

Why is compile time important?

If we have to wait for the compilation part, that slows down the entire workflow. And time is money. If one manages to optimise the compilation time down to a few milliseconds, then we can move on to testing our changes. If we need to wait hours until that step, that creates a bottleneck in the development.

What is recursion in programming?

Recursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself. For example, we can define the operation "find your way home" as: If you are at home, stop moving. Take one step toward home. "find your way home".


2 Answers

It repeatedly instantiates the f1<N> template with decreasing values for N (f1<N>() calls f1<N-1> 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<N> 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.

like image 103
Alexander Gessler Avatar answered Jan 05 '23 23:01

Alexander Gessler


It works conceptually almost the same way as runtime recursion. f1<1000> calls f1<999> and then prints out 1000. f1<999> calls f1<998> and then prints out 999, etc. Once it gets to 1 the template specialization acts as the base case to abort the recursion.

like image 42
Mark B Avatar answered Jan 06 '23 00:01

Mark B