Disappointing inflexibility of argument passing with "alias this"

Adam D. Ruppe via Digitalmars-d digitalmars-d at puremagic.com
Tue Feb 23 06:35:35 PST 2016


On Tuesday, 23 February 2016 at 14:29:27 UTC, NX wrote:
> The deal is you can't have implicit construction like:
> A a = 5; // Error

That is *explicit* construction and it is perfectly legal in D.

It is just done with constructors, not alias this. Alias this has 
absolutely nothing to do with construction, it plays zero role.

All alias this does is forward to a member object when you try to 
use it as a case where the outer type doesn't work but the inner 
type does. The object must already exist for this to happen, so 
it can't work on constructors.

> import std.stdio;
>
> struct A { int i; alias i this;}
> void f(int i){writeln("int");}
> void f(A a){writeln("A");}
>
> void g(A a){ f(a); }
>
> void main()
> {
>     g(A());
> }
>
> Above code prints "A". I would expect it to be an ambiguity 
> error. Not sure if I should file a bug report?

There's no ambiguity there and no bug; it is working as defined. 
alias this is only ever invoked if the outer type doesn't fit. It 
does fit here, A is A, so no need to check alias this at all.


More information about the Digitalmars-d mailing list