Compile-time associative array

boolangery eliott.dumeix at gmail.com
Wed Mar 20 08:11:27 UTC 2019


On Tuesday, 19 March 2019 at 23:41:58 UTC, Steven Schveighoffer 
wrote:
> On 3/19/19 7:22 PM, Bastiaan Veelo wrote:
>
>> Beware that a CT AA stores its elements in a different order 
>> than a RT AA, which you would notice in a foreach, for example.
>
> Yes, this is the issue -- the runtime AA depends on druntime, 
> which is not available to the compiler. The compiler has its 
> own AA implementation that it uses for CTFE.
>
> The internals will not be the same, which is why you can't 
> construct one at compile-time and use it at runtime (the enum 
> just recreates it at runtime when used).
>
> -Steve

Got it ! Thank you, so I need to write:

enum string[string] CtfeFoo = ["foo" : "bar"];
static immutable string[string] Foo;

static this()
{
     Foo = CtfeFoo;
}

string ctfeableFunction()
{
     if (__ctfe)
     	return CtfeFoo["foo"];
     else
         return Foo["foo"];
}

void main()
{
     enum a = ctfeableFunction();
     auto b = ctfeableFunction();
}


More information about the Digitalmars-d-learn mailing list