Is `alias this` a mistake?

jmh530 john.michael.hall at gmail.com
Wed Aug 4 15:13:07 UTC 2021


On Wednesday, 4 August 2021 at 14:32:17 UTC, bachmeier wrote:
> [snip]
>
> It's difficult to beat the simplicity of alias this. Even if 
> something cam be done with mixin templates, that's a lot of 
> overhead vs `alias x this;`. I can't say I use mixin templates 
> very often, but am skeptical that there's no way to misuse them.

I'm sympathetic to this.

I think if you got rid of alias this, then you would end up 
needing something else to accomplish some form of subtyping 
relationship for structs beyond just composition. For instance, 
the struct below can be used anywhere an int can be used. Without 
alias this, you either need to pull out that x value each time it 
is used in a function or you need to write overloads for all the 
functions you want to use Foo with like an int. Alternately, you 
can modify those functions to become generic and handle things 
that are like an int, but then what if you don't control those 
functions? It's just so simple.

```d
struct Foo {
     int x;
     alias x this;
}
```


More information about the Digitalmars-d mailing list