Advertisement
Guest User

Untitled

a guest
Jan 16th, 2012
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 0.96 KB | None | 0 0
  1. template fieldsOf (T)
  2. {
  3.     const fieldsOf = fieldsOfImpl!(T, 0);
  4. }
  5.  
  6. template fieldsOfImpl (T, size_t i)
  7. {
  8.     static if (T.tupleof.length == 0)
  9.         const fieldsOfImpl = [""];
  10.    
  11.     else static if (T.tupleof.length - 1 == i)
  12.         const fieldsOfImpl = [T.tupleof[i].stringof[1 + T.stringof.length + 2 .. $]];
  13.    
  14.     else
  15.         const fieldsOfImpl = T.tupleof[i].stringof[1 + T.stringof.length + 2 .. $] ~ fieldsOfImpl!(T, i + 1);
  16. }
  17.  
  18. template Fields ()
  19. {
  20.     alias typeof(this) This;
  21.    
  22.     static string __makeOpBinaryFields (string op) ()
  23.     {
  24.         string res;
  25.        
  26.         foreach (field ; fieldsOf!(This))
  27.             res ~= "res." ~ field ~ " = this." ~ field ~ op ~ " rhs." ~ field ~ ";\n";
  28.            
  29.         return res;
  30.     }
  31.    
  32.     This opBinary (string op) (This rhs)
  33.     {
  34.         This res;
  35.         mixin(__makeOpBinaryFields!(op));
  36.        
  37.         return res;
  38.     }
  39. }
  40.  
  41. struct Foo
  42. {
  43.     int x;
  44.     int y;
  45.    
  46.     mixin Fields;
  47. }
  48.  
  49.  
  50. void main ()
  51. {
  52.     Foo foo = Foo(3, 4);
  53.     Foo bar = Foo(5, 6);
  54.     auto r = foo + bar;
  55.     assert(r.x == 8);
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement