On Tuesday, 20 May 2014 at 21:04:37 UTC, anonymous wrote:
On Tuesday, 20 May 2014 at 20:15:09 UTC, Dominikus Dittes
Scherkl
wrote:
/// create a fixed size array with the given name and with
*max* entries
max + 1 entries
/// of immutable values of the same type as the return value
of the
/// given function.
/// it contains the values of that function in the range
[0..max].
string makeLookupTable(alias fn, uint max=255)(string name)
pure @safe if(is(typeof(fn(max))))
{
string table = "immutable " ~ to!string(typeof(fn(max))) ~
"[" ~ to!string(max+1) ~ "] " ~ name ~"= [ ";
foreach(i; 0..max) table ~= to!string(fn(i) ~ ", ";
return table ~ to!string(fn(max) ~" ]";
}
Couldn't resist purging that of the string fiddling:
...
enum ReturnType!fn[length] lookupTable = [elements];
Depending on what the usecase is, you might want to change that
to static immutable instead:
static immutable ReturnType!fn[length] lookupTable = [elements];
Remember that when using an enum, the compiler will create a
*new* variable on every use. While the compiler can sometimes
avoid actually allocating, it may also insert some object code
bloat to do so.