Limited Semi-PolyMorphic (LSP) structs?

Era Scarecrow rtcvb32 at yahoo.com
Wed Aug 28 04:34:10 PDT 2013


  K got a prototype working, I know there's issues with it but for 
now it looks simple and acts the way it is suppose to (at least 
to the unittest) so... Had to use templates through all the 
functions in order for auto ref to work right (hopefully forwards 
what it needs...)


/*
   //the only thing i would need to update, wish i didn't have to 
though...
   enum entries = ["iA:A,C",
                   "iB:A,B"];

   //AB as the base struct. 'real_' defaulted for the real 
functions.
   mixin(LSPS("AB", entries));
*/

     //generated output - start
     struct AB {
       LSPS_Type type;
       auto ref A(T...)(auto ref T t) {
         void* ptr = &this;
         with(LSPS_Type) { switch(type) {
           case LSPS_iB: return (cast(iB*) ptr).real_A(t);
           default: return (cast(iA*) ptr).real_A(t);
         }}
     }

       auto ref B(T...)(auto ref T t) {
         void* ptr = &this;
         with(LSPS_Type) { switch(type) {
           case LSPS_iB: return (cast(iB*) ptr).real_B(t);
           default: throw new Exception("Function 'B' not 
avaliable for subtype of "~to!string(type)~"");
         }}
       }

       auto ref C(T...)(auto ref T t) {
         void* ptr = &this;
         return (cast(iA*) ptr).real_C(t);
       }

       enum LSPS_Type {LSPS_iA, LSPS_iB, }
     }
     //generated - end

     //the two structs that are inherited.
     struct iA {
       AB lsps; alias lsps this;
       string real_A(){ return "iA_A";}
       string real_C(){ return "iA_C";}
     }
     struct iB {
       AB lsps; alias lsps this;
       string real_A(){ return "iB_A";}
       string real_B(){ return "iB_B";}
     }

   //Doesn't matter if it's iA, iB or AB, it should act the same
   iA ab;
   assert(ab.A() == "iA_A");
   assertThrown(ab.B());
   assert(ab.C() == "iA_C");

   ab.type = AB.LSPS_Type.LSPS_iB;
   assert(ab.A() == "iB_A");
   assert(ab.B() == "iB_B");
   assert(ab.C() == "iA_C");


More information about the Digitalmars-d-learn mailing list