How to create a class-valued variable?

Benjamin Schaaf ben.schaaf at gmail.com
Wed Feb 20 04:29:36 UTC 2019


On Tuesday, 19 February 2019 at 22:04:58 UTC, Victor Porton wrote:
> What is the right way to store in a structure a class (not an 
> instance) derived from a given interface(s)?

What are you trying to do with the "class"? If you just want a 
static "reference" to it you can use an `alias`:

   class A {}
   struct B {
     alias C = A;
   }
   new B.C();

If you want dynamic information on the type you can use TypeInfo:

   class A {}
   struct B {
     TypeInfo i;
   }
   B b;
   b.i = typeid(A);
   b.i.factory();

Or more simply if you just want to construct instances, just use 
a delegate:

   interface I {}
   class A : I {}
   struct B {
     I delegate() factory;
   }
   B b;
   b.factory = () => new A();
   b.factory();

You *can't* do something like the following because types need to 
be validated at compile time:

   struct A {
     Class cls;
   }
   A a;
   a.cls b;
   b.run();


More information about the Digitalmars-d-learn mailing list