Constructor called instead of opAssign()

frame frame86 at live.com
Sun Feb 14 07:09:20 UTC 2021


I have generic types that are initialized by a base class for 
each derived object:

struct S(T) {
     this(T val) {
         value = 100;
     }

     void opAssign(T val) {
         value = val;
     }

     T value;
}

class A {
     this(this T)() {
         foreach (property; __traits(allMembers, T)) {
             static if (property == "x") {
                 __traits(getMember, cast(T) this, property) = 50;
             }
         }
     }
}

class B : A {
     S!int x;

     this(int val) {
        assert(x.value == 50);
        x = val;
     }
}

auto b = new B(200);
assert(b.x.value == 200); // 100


Although x is well initialized by A by calling opAssign(), the 
compiler doesn't care and calls the S!T ctor() on B again and 
opAssign() is ignored. Is this a bug or a rule?


More information about the Digitalmars-d-learn mailing list