Guest User

Untitled

a guest
Oct 15th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.00 KB | None | 0 0
  1. /*
  2.  * custom (extendable) functions
  3.  * it is also possible to make custom variable types using operator overloading
  4.  *
  5.  */
  6.  
  7. import std.stdio;
  8.  
  9.  
  10. // this is generic
  11. mixin template extensions () {
  12.   auto opDispatch (string fn, args...) (args arguments) {
  13.       mixin("return " ~ fn ~ "(this, arguments);");
  14.   }
  15. }
  16.  
  17.  
  18. // out custom variable
  19. struct myInt {
  20.  
  21.   mixin extensions;
  22.  
  23.   int value = 0;
  24.  
  25.   myInt customAdd (int value) {
  26.     myInt newInt;
  27.     newInt.value = this.value + value;
  28.     return newInt;
  29.   }
  30.  
  31. }
  32.  
  33. myInt otherAdd (myInt i, int value) {
  34.   myInt newInt;
  35.   newInt.value = i.value + value;
  36.   return newInt;
  37. }
  38.  
  39.  
  40. void main () {
  41.   writeln("start");
  42.  
  43.   myInt i1;
  44.   i1.value = 3;
  45.   writeln(i1.value); // 3
  46.  
  47.   myInt i2 = i1.customAdd(2);
  48.   writeln(i2.value); // 5
  49.  
  50.   myInt i3 = i2.otherAdd(1);
  51.   writeln(i3.value); // 6
  52.  
  53.   myInt delegate (int) fp;
  54.   fp = &i3.opDispatch!("otherAdd", int);
  55.   myInt i4 = fp(2);
  56.   writeln(i4.value); // 8
  57.  
  58.   writeln("end");
  59. }
Add Comment
Please, Sign In to add comment