digitalmars.D.learn - How add class or struct member after construction?
- Marcone (2/2) Nov 05 2020 How add class or struct member after construction? Is it possible
- H. S. Teoh (9/11) Nov 05 2020 You can't, because D is statically-typed.
- Simen =?UTF-8?B?S2rDpnLDpXM=?= (23/25) Nov 05 2020 This depends a lot on what you mean. The short answer is no - you
- Jacob Carlborg (17/19) Nov 08 2020 It depends on what needs you have. You can declare a free function that
How add class or struct member after construction? Is it possible in D? How?
Nov 05 2020
On Thu, Nov 05, 2020 at 10:48:38PM +0000, Marcone via Digitalmars-d-learn wrote:How add class or struct member after construction? Is it possible in D? How?You can't, because D is statically-typed. However, you *can* implement something equivalent manually by other means, depending on your use case. What use do you have in mind? If you're more specific about what you're trying to accomplish, we could figure out a possible implementation for you. T -- Why waste time learning, when ignorance is instantaneous? -- Hobbes, from Calvin & Hobbes
Nov 05 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
Nov 05 2020
On 2020-11-05 23:48, Marcone wrote:How add class or struct member after construction? Is it possible in D? How?It depends on what needs you have. You can declare a free function that takes the class/struct as the first parameter and call it like a method [1]: class Foo { int a; } void printA(Foo foo) { writeln(foo.a); } foo.printA(); printA(foo); The two above lines are exactly the same. [1] https://dlang.org/spec/function.html#pseudo-member -- /Jacob Carlborg
Nov 08 2020