On 25/06/14 17:33, bearophile via Digitalmars-d wrote:
In D we have "alias this" that inside a struct allows to create a new type (with
instance object of size equal or larger than the original type) with similar
semantics of a given type. This allows to define a type that acts "like" 
another.

I'd like to mention that this has an unfortunate issue with respect to encapsulation of data. See:
http://d.puremagic.com/issues/show_bug.cgi?id=10996

The problem is that if you have a subtype implemented via alias this,

    struct Foo
    {
        SomeOtherStruct payload;
        alias payload this;

        // ... other stuff ...
    }

... then ideally you'd like the payload field to be private, because otherwise you're exposing implementation details, which could be nasty if you ever want to alter the design. (SOMEONE using your code is going to wind up assuming that accessing payload directly is OK.)

However, if you try and implement it this way,

    struct Foo
    {
        private SomeOtherStruct payload;
        public alias payload this;

        // ... other stuff ...
    }

... the compiler won't accept it, because the private access to payload clashes with public access via alias this.

It's a shame, because the principle -- payload is private, but public access to its fields is available via the alias this -- is a nice one; and it's clearly something that was envisioned for the language (TDPL p. 232, I think).

Personally, I'd really appreciate it if the above-mentioned issue could get some compiler dev attention. :-)

Reply via email to