The relationship of invariants and alias this

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Tue Nov 11 05:11:54 PST 2014


On 11/11/14 6:48 AM, ZombineDev wrote:
> AFAIU, even if you had a getter in the alias this:
>
> ---
> import std.stdio;
>
> struct ValueRestrictedInteger(int lowerBound, int upperBound) {
>    int value;
>    auto ref get() { return value; }
>    alias get this;
>
>    this (int rhs) { value = rhs; }
>
>    invariant() {
>      assert (value >= lowerBound && value <= upperBound);
>    }
>
>    void forDemonstrationOnly() {}
> }
> ---
>
> It would still not work:
>
> ---
> unittest {
>    ValueRestrictedInteger!(0, 100) x = 0;
>
>    x -= 100; //is probably lowered to something like this:
>    // 1) invariant();
>    // 2) int* __temp = &x.value; // this is what get() does
>    // 3) invariant();
>    // 4) *__temp = *temp - 100;
>
>    //...
> }
> ---
>
> Obviously, 4) will not trigger the invariant because it doesn't call any
> public functions.

Correct, the only real solution is to wrap with the actual operators and 
opDispatch.

-Steve


More information about the Digitalmars-d mailing list