Implementing interfaces using alias this

basile b. via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jun 14 14:04:55 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.
>
> import std.stdio;
>
> interface IDuck
> {
>     void quack();
> }
>
> class Test(T) : IDuck
> {
>     T data;
>     alias data this;
> }
>
> struct Duck
> {
>     void quack()
>     {
>         writeln("Quack");
>     }
> }
>
>
> void main()
> {
> 	Test!Duck d;
> }

The way to do that in D is with mixins:

interface IDuck
{
     void quack();
}

class Test(alias MyImpl) : IDuck
{
     mixin MyImpl;
}

mixin template DuckImpl()
{
     void quack()
     {
         import std.stdio;
         writeln("Quack Quack");
     }
}

void main()
{
     (new Test!DuckImpl).quack;
}


More information about the Digitalmars-d-learn mailing list