Template limits in D2

Lutger lutger.blijdestijn at gmail.com
Sun May 24 08:37:49 PDT 2009


bearophile wrote:

... 
> 
> The second problem is that compile-time functions are nicer, so I'd like to not use templates when possible. But the following code doesn't work at compile time, can you tell me why? (I have had to use a 
not nice temporary struct to return the static array)
> 
> struct S(int N) { int[N] a; }
> 
> S!(N) genSquares(int N)() {
>     S!(N) s;
>     for (int i = 0; i < N; i++) {
>         int n = i;
>         int m = 0;
>         while (n) {
>             int digit = n % 10;
>             n /= 10;
>             m += digit * digit;
>         }
>         s.a[i] = m;
>     }
> 
>     return s;
> }
> void main() {
>     const int CHUNK = 1000;
>     static const auto squares = genSquares!(CHUNK)().a;
> }
> 
> Bye and thank you,
> bearophile

I'm not sure why, this code does work:

int[] genSquares(int N)()
{
    int[] a;
    
    for (int i = 0; i < N; i++)
    {
        int n = i;
        int m = 0;

        while (n)
        {
            int digit = n % 10;
            n /= 10;
            m += digit * digit;
        }
        a~=m;
    }
    return a;
}

void main() {
    enum int CHUNK = 1000;
    enum int[CHUNK] squares = genSquares!(CHUNK)();
}

However, it fails as soon as I try do use indexing or set the length of an array. I thought these operations were supposed to be legal, perhaps it is a bug.




More information about the Digitalmars-d-learn mailing list