Python's list equivalent with std.variant?

Ali Çehreli acehreli at yahoo.com
Mon Oct 4 00:27:32 UTC 2021


On 10/3/21 3:22 PM, rjkilpatrick wrote:

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

I notice your code comment about SuperClass[]. It is still the most 
obvious solution here. You just need to check the reuslt of a 
cast(DerivedClass):

import std.stdio : writefln;
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

   // [Ali]: When you must know what the exact derived type you
   //        are using, generally there is a better approach.
   //
   //        Assuming that you really want to "downcast", then you
   //        simply cast to DerivedClass and see whether the
   //        pointer is null or not. (See below.)

   SuperClass[] list;

   // Attempting to append derived class instances to list
   list ~= new DerivedClass(1.0f);
   list ~= new OtherDerivedClass;

   foreach (i, item; list) {
     auto p = cast(DerivedClass)item;

     if (p) {
       writefln!"%s: Yes, a DerivedClass object with a == %s."(i, p.a);

     } else {
       writefln!"%s: No, not a DerivedClass object."(i);
     }
   }
}

Ali



More information about the Digitalmars-d-learn mailing list