On Thu, Aug 05, 2021 at 03:09:13PM +0000, someone via Digitalmars-d-learn wrote:
> On Thursday, 5 August 2021 at 10:28:00 UTC, Steven Schveighoffer wrote:
> 
> > H.S. Teoh, I know you know better than this ;) None of this is
> > necessary, you just need `rtValue` for both runtime and CTFE (and
> > compile time parameters)!

Haha, I haven't used this particular feature of D recently, so probably
my memory is failing me. ;-)


> > Now, the original question is about *associative arrays*, which are
> > a different animal. Those, you actually have to initialize using a
> > static constructor, and does indeed need both an enum and a static
> > immutable, as CTFE currently does not understand runtime AAs. This
> > is a huge issue since you do need silly things like the `if(__ctfe)`
> > statement you wrote, and keep an enum handy for those cases which is
> > identical to the static immutable. We really need to fix this.
> 
> When you say "We really need to fix this" you mean that *eventually*
> associative-arrays will be available at compile-time ?
[...]

AA's are already available at compile-time.  You can define them in CTFE
and pass them around as template arguments.

What doesn't work is initializing global static immutable AA's with
literals. Currently, you need this workaround:

        struct Data { /* whatever you want to store here */ }
        static immutable Data[string] aa;
        shared static this() {
                aa = [
                        "abc": Data(...),
                        "def": Data(...),
                        // ... etc.
                ];
        }

Unfortunately, this also means you can't access the value of `aa` at
compile-time. So you need a separate enum in order to access AA values
at compile-time.

Full runnable example:
---------------
enum ctValue = [
        "abc": 123,
        "def": 456,
];

static immutable int[string] rtValue;
shared static this() {
        rtValue = ctValue;
}

// Compile-time operations
enum x = ctValue["abc"];
enum y = ctValue["def"];
static assert(x == 123 && y == 456);

// Runtime operations
void main() {
        assert(rtValue["abc"] == 123);
        assert(rtValue["def"] == 456);
}
---------------


T

-- 
My father told me I wasn't at all afraid of hard work. I could lie down right 
next to it and go to sleep. -- Walter Bright

Reply via email to