Compile time range checking/asserts

bearophile bearophileHUGS at lycos.com
Wed Sep 15 05:20:09 PDT 2010


Borden Rhodes:
> <code>int gear {1...6} = 1;</code>

I think Walter said that Ranged Types are a "failed feature" of Pascal/Ada lineage, but I don't agree and I think they are useful to increase code safety, a possible syntax from yours:

typedef int { 1 ... 6 } Gear;

Using a struct with "alias this" and a struct invariant that enforces the range, plus properties, is possible, but such struct:
- Doesn't act transparently as a int subclass;
- Syntax-wise it's longer to define;
- The invariant is not enforced in all situations.

struct Gear {
    int g_ = 1;
    this(int g) { this.g_ = g; }
    invariant() { assert(this.g_ >= 1 && this.g_ <= 6); }
    @property void g(int x) { this.g_ = x; }
    @property int g() { return this.g_; }
    alias g this;
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list