Automatic method overriding in sub-classes

Daniel N via Digitalmars-d digitalmars-d at puremagic.com
Thu Oct 29 10:32:17 PDT 2015


On Thursday, 29 October 2015 at 13:54:17 UTC, bitwise wrote:
>> class One : Base!One { }
>> class Two : Base!Two { }
>
> Doesn't work with multiple levels of inheritance...
>
>     Bit

Just sprinkle some D magic ontop.. voilĂ  DRTP is born ;)

template Dynamic(T)
{
   static if(is(T == U!V, alias U, V))
     alias Dynamic = Dynamic!V;
   else
     alias Dynamic = T;
}

interface IBase { string Name(); }

class Base(T) : IBase
{
   final string Name()
   {
     auto self = cast(Dynamic!T)this;

     return self.me; // Dynamic!T.stringof;
   }
}

class One(T...) : Base!One { string me = "1";}
class Two(T...) : Base!Two { string me = "2";}
class Six(T...) : One!Six  { string me = "6";}
class Ten(T...) : Six!Ten  { string me = "a";}

void main()
{
   import std.stdio;

   IBase one = new One!();
   IBase two = new Two!();
   IBase six = new Six!();
   IBase ten = new Ten!();

   one.Name.writeln;
   two.Name.writeln;
   six.Name.writeln;
   ten.Name.writeln;
}


More information about the Digitalmars-d mailing list