Template limits

bearophile bearophileHUGS at lycos.com
Mon May 25 02:57:39 PDT 2009


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?

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.

Bye,
bearophile



More information about the Digitalmars-d mailing list