Walter Bright wrote:
> Lots of bugs fixed. -fPIC code gen fixes, should be a big step towards
> shared library support under Linux.
>
> http://www.digitalmars.com/d/changelog.html
And as a result of the template bug fixes, this is now possible:
--------------------------------------
// Create a constant array of int or uint sized items
// as a dchar[] string. n is the index of the last item.
template makeLookup(alias entry, int n)
{
static if (n == -1) // start with an empty array...
const dchar [] makeLookup = "";
else // ... and fill it up
const dchar [] makeLookup = makeLookup!(entry, n-1)
~ cast(dchar)entry!(n);
}
// only needed to workaround a DMD 0.145 bug
template LookupTable(alias entry, int n)
{
const LookupTable = cast(typeof(entry!(0)) [])makeLookup!(entry, n);
}
// USAGE: Let's make a factorial lookup table
template factorial(uint n)
{
static if (n<2) const uint factorial = 1;
else const factorial = n * factorial!(n-1);
}
// Make an array of all the factorials from 0 to 13 (14!> uint.max)
const smallfactorials = LookupTable!(factorial, 13);
import std.stdio;
void main()
{
for (int i=0; i<smallfactorials.length; ++i)
writefln(i, " ", smallfactorials[i]);
}
--------------------------------------
I've wanted to do this in C++ for a very long time. I thought that we
would need array literals to be able to do this. Apparently not.
Also note the extensive use of type inference!
If there was some way at compile time of doing a reinterpret_cast() from
any type to an array of bytes, the LookupTable function could be made to
work for ANY type whatsoever, with negligible increase in complexity.
(just need to change cast(dchar) to something like
reinterpret_cast(char[])).
But, I even wonder if could be made to work without any casts at all. I
can see that array literals are difficult in the general case. But here,
all of the types are known. Would it be possible to do constant folding
on arbitrary arrays, even before array literals are implemented?