Associative arrays give compile error

bearophile bearophileHUGS at lycos.com
Tue Oct 5 10:10:49 PDT 2010


> enum E_MODE {
>     LSB,  //  0
>     USB,  //  1
>     DSB,  //  2
>     CWL,  //  3
>     CWU,  //  4
>     FMN,  //  5
>     AM,   //  6
>     DIGU, //  7
>     SPEC, //  8
>     DIGL, //  9
>     SAM,  // 10
>     DRM   // 11
> }
> 
> void main() {
>     // associative array for translation
>     with (E_MODE) immutable auto a_mode = [
>             "LSB":  LSB,
>             "USB":  USB,
>             "DSB":  DSB,
>             "CWL":  CWL,
>             "CWU":  CWU,
>             "FMN":  FMN,
>             "AM":   AM,
>             "DIGU": DIGU,
>             "SPEC": SPEC,
>             "DIGL": DIGL,
>             "SAM":  SAM,
>             "DRM":  DRM
>         ];
> }

That code of mine is not good. The following version is more DRY, and in theory it's a better, but in practice it doesn't work:


import std.stdio: writeln;

enum E_MODE {
    LSB,
    USB,
    DSB,
    CWL,
    CWU,
    FMN,
    AM,
    DIGU,
    SPEC,
    DIGL,
    SAM,
    DRM
}

/*immutable*/ E_MODE[string] a_mode;

static this () {
    foreach (m; __traits(allMembers, E_MODE))
        mixin(`a_mode["` ~ m ~ `"] = E_MODE.` ~ m ~ `;`);
}

void main() {
    writeln(a_mode);
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list