How do I use CTFE to generate an immutable associative array at compile time?

Era Scarecrow via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 21 21:02:21 PST 2017


On Tuesday, 21 February 2017 at 22:34:57 UTC, Chad Joan wrote:
> In this case the AA isn't actually coded into the executable; 
> but at least the configuration from some_data.csv will be in 
> the executable as a string.  The program will construct the AA 
> at startup.  It's not as "cool", but it should get the job done.

  I have a partial static AA implementation that seems like it 
works, I mentioned this in a different thread.

https://github.com/rtcvb32/Side-Projects/blob/master/staticaa.d

Try it out, etc.

Usage:
Create your AA as an enum (for simplicity)

StaticAA!(KeyType, ValueType, getAALen(EnumAssosiativeArray), 
EnumAssosiativeArray.length)(EnumAssosiativeArray);

Afterwards use it as you normally would for the same thing.

Unittest example:

enum AA = ["one":1, "two":2, "three":3, "four":4, "five":5, 
"six":6, "seven":7, "eight":8, "nine":9, "zero":0];
auto SAA = StaticAA!(string, int, getAALen(AA), AA.length)(AA);

   //just verifies the keys/values match.
   foreach(k, v; AA) {
     assert(SAA[k] == v);
   }


Note: getAALen basically tests the array expanding it out until 
none of the hashes overlap or causes problems. Trying to compile 
these into a single call I've had issues, so if anyone has a 
better solution I'd go for it.


More information about the Digitalmars-d-learn mailing list