www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Alias this and inheritance

reply Aurelien Fredouelle <aurelien.fredouelle+dlang gmail.com> writes:
The following code does not compile:

struct S { }

class A
{
   S s;
   alias s this;
}

class B : A
{
}

void main()
{
   A asA = new B;
   B asB = cast(B)asA;
}

I would expect the last line to successfully cast the B instance 
I created back into type B, however this seems to be preempted by 
the alias this:

Error: cannot cast expression asA.s of type S to app.B

Is there a way to force this cast to operate on the object of 
type A instead of automatically using A.s?

Thanks,
Aurelien
Nov 05
parent ag0aep6g <anonymous example.com> writes:
On Sunday, 5 November 2017 at 07:07:43 UTC, Aurelien Fredouelle 
wrote:
 struct S { }

 class A
 {
   S s;
   alias s this;
 }

 class B : A
 {
 }

 void main()
 {
   A asA = new B;
   B asB = cast(B)asA;
 }

 I would expect the last line to successfully cast the B 
 instance I created back into type B, however this seems to be 
 preempted by the alias this:

 Error: cannot cast expression asA.s of type S to app.B

 Is there a way to force this cast to operate on the object of 
 type A instead of automatically using A.s?
Known issue: https://issues.dlang.org/show_bug.cgi?id=6777 You can work around by casting to Object first: B asB = cast(B) cast(Object) asA;
Nov 05