Is `alias this` a mistake?

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Aug 5 16:46:53 UTC 2021


On Thu, Aug 05, 2021 at 03:49:25PM +0000, jmh530 via Digitalmars-d wrote:
> On Wednesday, 4 August 2021 at 16:45:27 UTC, H. S. Teoh wrote:
> > [snip]
> > 
> > This is why, even though I loved alias this (and still do to some
> > extent), I have come to realize that in the long term, it lies more
> > on the negative side of the scale than the positive.
[...]
> Goods points throughout. Thanks for your perspective.
> 
> You describe an issue with upcasting. Would something like this only
> work in the context of classes and reference types? In other words,
> suppose alias this was removed from the language, but some more formal
> inheritance scheme was introduced for structs. Would it be able to
> have that behavior?

In C++, structs also support OO-style inheritance, and upcasting /
downcasting works the same way as in classes.  So I suppose it could be
made to work.

Note, however, that the reason D structs don't support inheritance,
AIUI, is because of issues with this feature in C++. One of which is,
the size of a variable of that type. Since a derived class implicitly
converts to a base class, the same should apply to structs; but what
happens when you try to pass a derived struct to a function that takes a
base struct?  There would not be room to store the derived struct's
data, which means you can only pass the base portion of the struct to
the function.  Which in turn means overridden methods may try to access
data that isn't there. IOW, this violates the Liskov Substitution
Principle.

In C++, this is worked around by requiring passing by reference instead
by value. But in D, this kinda defeats the purpose of structs, the whole
point of which is a by-value type that gets passed around as "glorified
ints", as Andrei calls it.  Once you need to pass things around by
reference, structs lose their raison d'etre, and you might as well just
use a class instead.


T

-- 
Just because you can, doesn't mean you should.


More information about the Digitalmars-d mailing list