Enumap -- a lightweight AA alternative when your keys are enums

rcorre via Digitalmars-d-announce digitalmars-d-announce at puremagic.com
Thu Sep 10 21:02:15 PDT 2015


On Friday, 11 September 2015 at 03:25:58 UTC, SimonN wrote:
> Hi,
>
> this looks excellent! I've been playing around with it, and am 
> looking forward to using it regularly.
>
> I've ran into a compilation error when iterating over a const 
> Enumap. In the following code:
>
>     import std.stdio;
>     import std.conv;
>     import enumap;
>
>     enum MyEnum { e1, e2, e3 }
>
>     struct A
>     {
>         Enumap!(MyEnum, int) map;
>
>         void mutable_output()
>         {
>             foreach (MyEnum e, int i; map)
>                 writefln("%s: %d", e.to!string, i);
>         }
>
>         void const_output() const
>         {
>             foreach (MyEnum e, const int i; map)
>                 writefln("%s: %d", e.to!string, i);
>         }
>     }
>
> ...the first method (mutable_output) compiles and works with no 
> errors. The const method, however, gives:
>
>     source/app.d(19,13): Error: invalid foreach aggregate 
> this.map,
>     define opApply(), range primitives, or use .tupleof".
>
> It doesn't seem to matter whether I put const int, or int, in 
> the foreach statement.
>
> What's the idiomatic way to loop over a const Enumap? :-)
>
> -- Simon

Interesting, thanks for pointing that out.
I don't think I did a great job with const-correctness here, I'll 
take a look tomorrow.
It should definitely be possible to iterate over (and index, 
etc...) a const/immutable Enumset, though you're right that it 
doesn't work right now.


More information about the Digitalmars-d-announce mailing list