Error: need this for method of type
Hi! Consider this simplified program: ``` import std.stdio; struct X { void method(int x) { writeln("method called"); } } void main() { X x; foreach (member; __traits(allMembers, X)) { alias method = __traits(getMember, x, member); method(1); } } ``` Output: test.d(15): Error: need this for method of type void(int x) This one as well: ``` import std.stdio; struct X { void method(int x) { writeln("method(int) called"); } } struct Y { void method(ref X x) { foreach (member; __traits(allMembers, X)) { alias method = __traits(getMember, x, member); method(1); } } } void main() { Y y; X x; y.method(x); } ``` Output: ```test.d(14): Error: this for method needs to be type X not type Y``` This is a bug, right? If not, why, and how can I get around it and call `method`?
Re: Error: need this for method of type
On Wednesday, 23 October 2019 at 11:40:09 UTC, Márcio Martins wrote: This is a bug, right? If not, why, and how can I get around it and call `method`? An alias refers just to a symbol, in this case a member function of struct X. The fact that you polled it on instance 'x' is not something an alias keeps track of. You can change `method(1)` into `x.method(1)` and it should work.
Re: Error: need this for method of type
On Wednesday, 23 October 2019 at 11:48:29 UTC, Dennis wrote: You can change `method(1)` into `x.method(1)` and it should work. Wait, but that's only because the local alias and member function have the same name 'method'. I think you just have to keep the method name as a string instead of an alias and use ` __traits(getMember, x, member)(3);` the moment you want to call it.