import std.stdio; struct Base{ void opAssign(T)(T x){ writeln("assigning : ",x); } } struct Derived{ Base parent; alias parent this; } void main() { Base a; a = 10; //ok Derived b; b = 20; //Error } Output: Error: function f937.Derived.opAssign (Derived p) is not callable using argument types (int)
Structs have opAssign defined by default. Alias this only forwards undefined lookups. Below is a workaround. import std.stdio : writeln; struct Base{ void opAssign(T)(T x){ writeln("assigning : ",x); } } struct Derived{ Base parent; alias parent this; void opAssign(T)(T x){ parent = x; } } void main() { Base a; a = 10; //ok Derived b; b = 20; //Error }
Ran into this today. If the compiler is going to generate an opAssign, it should generate one that forwards to the alias-this member. It should be something equivalent to adding the following overload to the existing generated opAssign: auto ref opAssign(T)(auto ref T val) if (!is(T == typeof(this)) && __traits(compiles, aliasThisMember = val)) { aliasThisMember = val; } BTW, thanks for the workaround. For a wrapped single alias-this member, it works perfectly.
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/19177 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB