Thread overview | ||||||
---|---|---|---|---|---|---|
|
November 05, 2020 How add class or struct member after construction? | ||||
---|---|---|---|---|
| ||||
How add class or struct member after construction? Is it possible in D? How? |
November 05, 2020 Re: How add class or struct member after construction? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Marcone | 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 |
November 05, 2020 Re: How add class or struct member after construction? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Marcone | 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
|
November 08, 2020 Re: How add class or struct member after construction? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Marcone | 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 |
Copyright © 1999-2021 by the D Language Foundation