Implementing interfaces using alias this

Jesse Phillips via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jun 15 11:49:58 PDT 2017


On Wednesday, 14 June 2017 at 09:34:27 UTC, Balagopal Komarath 
wrote:
> Why doesn't this work? The Test!Duck type has a void quack() 
> method but the compiler says it is not implemented.

You question was answered, but you can do this:

------------------
     interface IDuck
     {
         void quack();
     }

     struct Duck
     {
         void quack()
         {
     		import std.stdio : writeln;
             writeln("Quack");
         }
     }


     void main()
     {
     	Duck d;
     	import std.experimental.typecons : wrap;
     	IDuck i = wrap!IDuck(d);
     	i.quack();
     }
-----------------

Please note that you can't wrap to an interface which returns 
itself

interface IDuck {
     IDuck clone();
}

It fails because the struct would return a Duck and wouldn't wrap 
it to an IDuck. This is only a limitation on wrap because I 
haven't written the detection and appropriate wrapping function 
call.


More information about the Digitalmars-d-learn mailing list