www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - alias this and shadowing

reply Jonathan Shamir <jonathan weka.io> writes:
I think the following example is legitimate code that should work:

struct S1 {
     void foo() {
         writeln("S1.foo()");
     }
     void foo(ulong x) {
         writefln("S1.foo(%d)", x);
     }
}

struct S2 {
     S1 s;
     alias s this;

     void foo(string str) {
         writeln("S2.foo(%s)", str);
     }
}

void main() {
     S2 s;

     s.foo("hahaha");
     s.foo(100);  // XXX this doesn't compile, since there's no 
S2.foo that accepts an int
}


To quote Andrei, if it looks like it should work, it should. 
(Also something about turtles).

My original code did something a bit different, just to show 
another example of why this behavior looks fundamentally broken 
to me:

struct S2 {
     S1 s;
     alias s this;
      disable void foo(ulong); // calling foo(ulong) doesn't make 
sense in the context of S2
}

Now, calling S2.foo() won't compile, since S2 only knows one 
prototype for foo which accepts a ulong.
Jun 15
parent Adam D. Ruppe <destructionator gmail.com> writes:
On Thursday, 15 June 2017 at 15:01:27 UTC, Jonathan Shamir wrote:
 To quote Andrei, if it looks like it should work, it should. 
 (Also something about turtles).
Hmm, interestingly, even if you explicitly merge the overloads with `alias foo s.foo;` (which is required btw, see: http://dlang.org/hijack.html ) but even doing that here gives Error: this for foo needs to be type S1 not type S2 and I actually would expect alias this to be invoked there to make it work.
Jun 15