Template class with dispatched properties

Chris Cain clcain at uncg.edu
Thu Nov 7 19:03:16 PST 2013


On Friday, 8 November 2013 at 02:48:31 UTC, Chris Cain wrote:
> Minor tweaks might be necessary, but that should get you 
> started.

Actually, I refactored it a little bit to make it better 
(original code was just a bit too messy for my taste):

---
struct Vector(int N, T) if (N <= 3) {
   private T[N] data;

   private static size_t toOffset(string fieldName) {
     return cast(size_t)(fieldName[0] - 'x');
   }

   public @property
   auto opDispatch(string fieldName, Args ...)(Args args)
   if (Args.length < 2
       && fieldName.length == 1
       && toOffset(fieldName) < N) {
     static immutable offset = toOffset(fieldName);
     static if(Args.length == 0) {
       // getter
       return data[offset];
     } else {
       // setter
       data[offset] = args[0];
     }
   }
}
---


More information about the Digitalmars-d-learn mailing list