Compile-time associative array

Bastiaan Veelo Bastiaan at Veelo.net
Tue Mar 19 23:22:52 UTC 2019


On Tuesday, 19 March 2019 at 08:50:15 UTC, boolangery wrote:
> Hi,
>
> I want to use a constant associative array in a ctfe-able 
> function.
>
> Example:
>
> string ctfeableFunction()
> {
>     return Foo["foo"];
> }
>
> Then I force ctfe with:
>
> enum res = ctfeableFunction();
>
> When I use an enum like:
>
> enum Foo = ["foo" : "bar"];
>
> It works fine.
>
> D-Scanner keep saying to me: This enum may lead to unnecessary 
> allocation at run-time. Use 'static immutable [...] instead'
>
> But it lead to: Error: static variable Foo cannot be read at 
> compile time.
>
> So is the only way to make ctfe-able associative array is to 
> use enum instead of static immutable ?

Yes, I think so. If you would use the enum AA multiple times, it 
would allocate a new AA each time, that is wat D-Scanner warns 
against. I am not sure how the CTFE interpreter is implemented, 
it could be that a new AA is allocated each time you call 
ctfeableFunction, at compile time. But unless you also call it at 
runtime, there should be no extra run time allocations.

If you need the AA at run time as well, I would create a static 
immutable version for that, initialised with the enum.

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.


More information about the Digitalmars-d-learn mailing list