enforcing alias this on derived types

Marco Leise Marco.Leise at gmx.de
Mon Jul 8 09:10:17 PDT 2013


Am Mon, 08 Jul 2013 10:59:14 +0200
schrieb "JS" <js.mdnq at gmail.com>:

> 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
> }

Interfaces only declare functions and have no state. What you
do looks like you actually want to give the interface state
through the "alias ... this" crutch. This is where you
use abstract classes if possible:

abstract class A(T)
{
     private T _value;
     @property T Value() { return _value; }
     @property T Value(T value) { return value = _value; }
     alias _value this;
}

class B(T) : A!T
{
}

I have only used "alias ... this" with structs and not
tested this code. Generally I try to avoid mixing the
realms of value types and class types in D like you
are trying to. It gives me a bad gut feeling.

In the OOP world I'd say, just use "obj.Value" everywhere
you want your object to work like type T.

-- 
Marco



More information about the Digitalmars-d-learn mailing list