On Monday, 8 July 2013 at 08:59:16 UTC, JS wrote:
I have an interface that I would like to make sure that any classes derived from it will use alias this, else it can potentially break code.

interface A(T)
{
    @property T Value();
    @property T Value(T value);
    // need to enforce alias _value this somehow
}

class B(T) : A!T
{
    private T _value;
    @property T Value() { return _value; }
    @property T Value(T value) { return value = _value; }
    alias _value this;
    // B must use alias this so B(T) behaves like type T
}

I can't think of a neat way to do this. However,if you don't mind a nasty solution:

You can just force the derived class writer to write a function that checks. Even if they just put in a no-op, it acts as a very solid reminder that will also be visible to anyone else reading their code.

struct S{}

interface I
{
        void checkForAliasThis();
}

class A : I
{
        void checkForAliasThis()
        {
                static assert(is(typeof(this) : S));
        }
        
        S s;
        alias s this;
}


Most other solutions I tried failed because the compiler evaluates the check (e.g. out contracts) in the interface, which makes the check either semantically wrong, or statically false/failed.

Reply via email to