fork download
  1. import std.exception, std.stdio;
  2.  
  3. struct CustomInteger(T, T minValue, T maxValue)
  4. {
  5. T value_;
  6.  
  7. alias value this;
  8.  
  9. @property T value() const
  10. {
  11. enforce((value_ >= minValue) &&
  12. (value_ <= maxValue));
  13.  
  14. return value_;
  15. }
  16.  
  17. @property void value(T v)
  18. {
  19. value_ = v;
  20. }
  21.  
  22. ref CustomInteger opOpAssign(string op, T2)(T2 rhs)
  23. {
  24. static if (is (T2 == CustomInteger)) {
  25. mixin("value_ " ~ op ~ "= rhs.value_;");
  26. return this;
  27.  
  28. } else {
  29. return opOpAssign!op(CustomInteger(rhs));
  30. }
  31. }
  32.  
  33. }
  34.  
  35. void main()
  36. {
  37. alias Balance = CustomInteger!(int, -32_000, 32_000);
  38.  
  39. auto b = Balance(42);
  40.  
  41. b += 5; // OK
  42.  
  43. writeln(b); // 47
  44. }
Success #stdin #stdout 0s 4152KB
stdin
Standard input is empty
stdout
47