digitalmars.D.learn - Unable to use map() and array() inside a class-field's initializer.
- realhet (30/30) Jul 14 2022 Hello,
- Paul Backus (9/30) Jul 14 2022 Simpler workaround:
- realhet (4/5) Jul 14 2022 Thank You!
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; } auto initialS(){ return [EnumMembers!E].map!(e => S(e)).array; } class C{ auto x = initialS; //this way it works } void main(){ writeln((new C).x); } ```
Jul 14 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.
Jul 14 2022
On Thursday, 14 July 2022 at 14:41:53 UTC, Paul Backus wrote:Explicit type annotation: vvvThank You! I will remember that in case of weird errors I can try to help the compiler with type inference.
Jul 14 2022