I've encountered something which is probably intentional behavior, but that I think is interesting and may merit discussion. When you do "alias this" and have an invariant, any methods that are forwarded to the aliased member do not invoke your invariant methods.

This prevents me from writing a really sleek 10-liner to the tune of:

struct ValueRestrictedInteger(int lowerBound, int upperBound) {
  int value;
  alias value this;

  this (int rhs) { value = rhs; }

  invariant() {
    assert (value >= lowerBound && value <= upperBound);
  }

  void forDemonstrationOnly() {}
}

unittest {
  ValueRestrictedInteger!(0, 100) x = 0;
  x += 10;
  x -= 100; //This works, but I don't think it should
  x.forDemonstrationOnly(); //This causes the assertion to fire

ValueRestrictedInteger!(0, 100) y = -100; //This also would hit the assertion
}

I realize that this is not the most efficient way to implement this concept and that the invariant gets compiled out in a -release build... I still think this is a pretty nifty piece of code whose semantics are not unreasonable. Why shouldn't an aliased method be subject to our invariants?

Reply via email to