I'm trying to create a type that for all intents and purposes behaves exactly like an int except that it limits its values to be within a certain range [a,b]. Theoretically, I would think this looks something like:

struct FixedRangeInt {
  this(int min, int max, int value=0) {
    this.min = min;
    this.max = max;
    this.value = value;
  }
  auto opDispatch(string name, T...)(T args) {
    auto backup = value;
    scope (failure) value = backup;
    auto result = mixin(`value.` ~ name ~ `(args)`);
    if (value < min || value > max) {
      throw new Exception("Operation put value out of range");
    }
    return result;
  }
  int min;
  int max;
  int value;
}

But that code doesn't work for simple cases, like:

FixedRangeInt(0, 100) x;
x += 5;

It looks like opDispatch doesn't participate in resolution of operator overloads. Is there any way I can achieve my desired result? I know alias this forwards operations like +=, but with alias this I cannot wrap the operation to do the bounds checking.

FWIW, the fixed range int part of this question is just an example, I'm mostly just interested in whether this idea is possible without a lot of bloat/duplication.

Reply via email to