Python's list equivalent with std.variant?
Kagamin
spam at here.lot
Tue Oct 5 15:16:43 UTC 2021
On Sunday, 3 October 2021 at 22:22:48 UTC, rjkilpatrick wrote:
> ```d
> import std.stdio : writeln;
> import std.variant;
> import std.conv;
>
> // Arbitrary super class
> class SuperClass {
> this() {
> }
> }
>
> // Derived class with members
> class DerivedClass : SuperClass {
> public:
> this(float a) {
> this.a = a;
> }
> float a;
> }
>
> class OtherDerivedClass : SuperClass {}
>
> void main() {
> // When we use `SuperClass[] list;` here, we find 'a' is
> hidden by the base class
> Variant[] list;
>
> // Attempting to append derived class instances to list
> list ~= new DerivedClass(1.0f);
> list ~= new OtherDerivedClass;
>
> list[0].a;
> list[0].to!(get!(list[0].type)).a.writeln;
> }
> ```
Looks like you want full duck typing. Dynamic objects are just
hashtables of properties, so an array of them is something like
this:
Variant[string][] list;
Variant[string] obj;
obj["a"]=Variant(1.0f);
list[0]["a"].get!float.writeln;
More information about the Digitalmars-d-learn
mailing list