Template recursion and compile-time evaluation.

Walter Bright newshound at digitalmars.com
Mon Aug 14 13:11:56 PDT 2006


Reiner Pope wrote:
> What are the rules about template recursion, and compile time evaluation 
> in general? For example, the following code produces an error on my 
> computer:
> 
> import std.stdio;
> 
> template count(uint n)
> {
>     static if (n == 0) const uint count = 0;
>     else const uint count = 1 + count!(n-1);
> }
> 
> int main(char[][] args)
> {
>     writefln("%d", count!(3008));
>     return 0;
> }
> 
> factorial.d(6): template instance factorial.count!(1u) recursive expansion

This happens when the compiler itself runs out of stack space. This 
amount will vary from machine to machine, operating system to operating 
system.

While the compiler is expected to do its best to accommodate recursion 
as much as possible, I recommend that for practical reasons one should 
think of a different algorithm if recursion levels more than 100 are used.



More information about the Digitalmars-d mailing list