Unable to use map() and array() inside a class-field's initializer.

Paul Backus snarwin at gmail.com
Thu Jul 14 14:41:53 UTC 2022


On Thursday, 14 July 2022 at 13:57:24 UTC, realhet wrote:
> Hello,
>
> Somehow it can't reach map and array inside a class field 
> initializer. If I put that small expression inside a function, 
> it works. If I encapsulate the initializer expression into a 
> lambda and evaluate it right away, it also works. Only the nice 
> form fails.
>
> Why is that?
>
> ```d
> import std;
>
> enum E{a, b, c}
>
> static struct S{
>     const E e;
>     string otherProperties;
> }
>
> //trying to initialize an array inside
>
> static if(1) class D{
>   //this fails: Error: function `onlineapp.D.map!(E[]).map` 
> need `this` to access member `map`
>   auto x = [EnumMembers!E].map!(e => S(e)).array;
> }
> ```

Simpler workaround:

```d
   // Explicit type annotation:   vvv
   auto x = [EnumMembers!E].map!((E e) => S(e)).array;
```

This turns the lambda from a template into a normal function, 
which apparently is enough to un-confuse the compiler. Still 
unclear why it's getting confused in the first place, though.


More information about the Digitalmars-d-learn mailing list