Template limits

Don nospam at nospam.com
Mon May 25 04:03:48 PDT 2009


bearophile wrote:
> This post is a partial copy of a post of mine from digitalmars.D.learn. Lot of people seem to ignore that place.
> 
> This is the only way I have found to create a certain static array at compile time:
> 
> int sumSqrt(int n) {
>     int result = 0;
>     while (n) {
>         int digit = n % 10;
>         n /= 10;
>         result += digit * digit;
>     }
>     return result;
> }
> template GenSquares(int n) {
>     static if (n < 0)
>         const int[] GenSquares = [];
>     else
>         const int[] GenSquares = GenSquares!(n-1) ~ [sumSqrt(n)];
> }
> void main() {
>     const int CHUNK = 1000;
>     static const auto squares = cast(int[CHUNK])GenSquares!(CHUNK-1);
> }
> 
> That code works with D1, but gives a "recursive expansion" error with D2, this is bad. Can D2 be fixed to have capabilities similar to D1?

It's a bug in D1, actually.  The bug was fixed in D2 but not yet in D1. 
As you increase the value, D1 will just silently segfault eventually. I 
believe D1 will be fixed in the next release.

> 
> I have also tried to write a nicer version of the code that uses just one compile-time function and no templates, and starts as:
> struct S(int N) { int[N] a; } 
> S!(N) genSquares(int N)() { ...
> 
> But so far I haven't found a way. If such limit is real, then I think D2 has to be improved to allow such things, because creating a fixed-size array at compile time is one of the main purposes of compile-time functions.

It's bug 2569. Nothing fundamental.



> 
> Bye,
> bearophile



More information about the Digitalmars-d mailing list