Re: Alias this and inheritance

2017-11-05 Thread ag0aep6g via Digitalmars-d-learn
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;



Alias this and inheritance

2017-11-05 Thread Aurelien Fredouelle via Digitalmars-d-learn

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


Re: alias this for inheritance

2011-02-23 Thread Steven Schveighoffer

On Wed, 23 Feb 2011 10:34:04 -0500, spir denis.s...@gmail.com wrote:


Hello,

I have read several times that alias this is a way to implement  
inheritance for structs.
I am simply unable to imagine how to use this feature that way. Has  
anyone an example?


It allows *some* simulation of inheritance.  However, it does not  
implement polymorphism.


What it does is allow specialization and upcasts.  For example:

struct S
{
   int x;
   void foo() {}
}

struct T
{
   S s;
   void foo2() {};
   int y;
   alias s this;
}

T t;
t.foo(); // translates to t.s.foo();
t.x = 5; // translates to t.s.x = 5;
S s = t; // translates to S s = t.s;

-Steve