Alias this and inheritance

2017-06-05 Thread Jacob Carlborg via Digitalmars-d

The following code does not compile:

void foo(string a) {}

class Base
{
alias bar this;

string bar()
{
return "";
}
}

class Sub : Base {}

void main()
{
auto sub = new Sub;
foo(sub);
}

But if the "alias this" is copied/moved to the subclass it works. Is 
this expected behavior?


--
/Jacob Carlborg


Re: Alias this and inheritance

2017-06-05 Thread ketmar via Digitalmars-d

Jacob Carlborg wrote:


The following code does not compile:

void foo(string a) {}

class Base
{
 alias bar this;

 string bar()
 {
 return "";
 }
}

class Sub : Base {}

void main()
{
 auto sub = new Sub;
 foo(sub);
}

But if the "alias this" is copied/moved to the subclass it works. Is this 
expected behavior?


yes, afaik. the reasons are similar to not automatically bringing overloads 
when you're doing override, and avoiding other "automatic helpers" most of 
the time: it can quickly get out of control.


Mixing struct and class subtypes with alias this and inheritance

2018-07-12 Thread Luís Marques via Digitalmars-d
You can define a struct subtype hierarchy by adding alias this 
declarations to each struct. Like this:


S3 <: S2 <: S1

struct S3 { auto toS2() { return S2(); } alias toS2 this; }
etc.

You can also define a class subtype hierarchy by using class 
inheritance:


C3 <: C2 <: C1

class C3 : C2 {}
etc.

But apparently the mechanisms don't mix. This works:

C1 <: S3 <: S2 <: S1

class C1 { auto toS3() { return S3(); } alias toS3 this; }

But this doesn't work:

C2 <: C1 <: S3 <: S2 <: S1

class C2 : C1 {}

I think that should work.

I know I can put an alias this in C2. But it seems like 
inheritance should be enough to bridge the gap, since subtyping 
should be transitive.