Thread overview
How add class or struct member after construction?
Nov 05, 2020
Marcone
Nov 05, 2020
H. S. Teoh
Nov 05, 2020
Simen Kjærås
Nov 08, 2020
Jacob Carlborg
November 05, 2020
How add class or struct member after construction? Is it possible in D? How?
November 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
November 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
November 08, 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