Template limits
Max Samukha
outer at space.com
Mon May 25 04:23:04 PDT 2009
On Mon, 25 May 2009 05:57:39 -0400, bearophile
<bearophileHUGS at lycos.com> 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?
>
>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
Your example can be rewritten like this:
int[] genSquares(int n)
{
int[] result;
for(; n >= 0; --n)
{
int k = n;
int m;
while (k) {
int digit = k % 10;
k /= 10;
m += digit * digit;
}
result = m ~ result;
}
return result;
}
void main() {
const int CHUNK = 1000;
static const auto squares = cast(int[CHUNK])genSquares(CHUNK - 1);
}
Works for both compiler versions.
More information about the Digitalmars-d
mailing list