Python's list equivalent with std.variant?

rjkilpatrick nothanks at example.com
Sun Oct 3 22:22:48 UTC 2021


Hi.

I am trying to emulate Python's list in D, to store some derived 
classes

My initial thought was to use a dynamic array of `std.variant`s.
I've tried implementing something but seeing as we can only 
instantiate templates at compile-time, and I may only know the 
type at run-time, I'm not sure how to go about this:

```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;
}
```

And we get the error(s):

```
onlineapp.d(27): Error: cannot append type 
`onlineapp.DerivedClass` to type `VariantN!32LU[]`
onlineapp.d(28): Error: cannot append type 
`onlineapp.OtherDerivedClass` to type `VariantN!32LU[]`
onlineapp.d(30): Error: no property `a` for type 
`std.variant.VariantN!32LU`
onlineapp.d(31): Error: template `object.get` does not match any 
template declaration
```

I would be grateful for any help


More information about the Digitalmars-d-learn mailing list