How add class or struct member after construction?

Simen Kjærås simen.kjaras at gmail.com
Thu Nov 5 23:01:15 UTC 2020


On Thursday, 5 November 2020 at 22:48:38 UTC, Marcone wrote:
> How add class or struct member after construction? Is it 
> possible in D? How?

This depends a lot on what you mean. The short answer is no - you 
cannot. However, given some limitations, it is possible. What 
sort of members do you need to add, and how will you be using 
them?

For instance, this works:

struct S {
     import std.variant;
     Variant[string] members;

     Variant opDispatch(string name)() {
         return members[name];
     }
     Variant opDispatch(string name, T)(T value) {
         return members[name] = value;
     }
}

unittest {
     S s;
     s.foo = 13;
     assert(s.foo == 13);
}

--
   Simen


More information about the Digitalmars-d-learn mailing list