Questions about opAssign alternate and template quality

nobody nobody at
Thu Aug 10 02:53:46 PDT 2006

I wanted to try out D's template system so I decided to define data structures 
that represent all the permutations of RGB, HLS, RGBA and HLSA. I decided to 
convert between the various types by overriding opAssign under the mistaken 
impression that D supported it. Impressive when you do the math:

     3! + 3! + 4! + 4! = 60 types
    (3! + 3! + 4! + 4!)^2 = 3600 opAssigns

So my first question is whether anyone has an elegant alternative to using opAssign?

My second question is mostly an open invitation to make suggestions for 
improving my template writing style. In particular I am suspicious that there is 
a way to take better advantage of templates and not write out all 60 permutations.

So here is the actual code. I only included the RGB permutations to keep it as 
short as possible.

union PixArray
   PixBGR[] bgr;
   PixBRG[] brg;
   PixGBR[] gbr;
   PixGRB[] grb;
   PixRBG[] rbg;
   PixRGB[] rgb;

template PixBGR_Perms_opAssignBGR(T,U)

   T opAssign(U that)
     ubyte tempB = that.b;
     ubyte tempG = that.g;
     ubyte tempR = that.r;
     this.b = tempB;
     this.g = tempG;
     this.r = tempR;
     return *this;


template PixBGR_Perms(T)
   alias b blue;
   alias g green;
   alias r red;

   // opAssign defined for all perms
   mixin PixBGR_Perms_opAssignBGR!(T,PixBGR);
   mixin PixBGR_Perms_opAssignBGR!(T,PixBRG);
   mixin PixBGR_Perms_opAssignBGR!(T,PixGBR);
   mixin PixBGR_Perms_opAssignBGR!(T,PixGRB);
   mixin PixBGR_Perms_opAssignBGR!(T,PixRBG);
   mixin PixBGR_Perms_opAssignBGR!(T,PixRGB);

   struct PixBGR { ubyte b; ubyte g; ubyte r; mixin PixBGR_Perms!(PixBGR); }
   struct PixBRG { ubyte b; ubyte r; ubyte g; mixin PixBGR_Perms!(PixBRG); }
   struct PixGBR { ubyte g; ubyte b; ubyte r; mixin PixBGR_Perms!(PixGBR); }
   struct PixGRB { ubyte g; ubyte r; ubyte b; mixin PixBGR_Perms!(PixGRB); }
   struct PixRBG { ubyte r; ubyte b; ubyte g; mixin PixBGR_Perms!(PixRBG); }
   struct PixRGB { ubyte r; ubyte g; ubyte b; mixin PixBGR_Perms!(PixRGB); }

More information about the Digitalmars-d-learn mailing list