Automatic method overriding in sub-classes
Daniel N via Digitalmars-d
digitalmars-d at puremagic.com
Thu Oct 29 01:27:03 PDT 2015
On Thursday, 29 October 2015 at 01:52:16 UTC, bitwise wrote:
> My argument though, is that a virtual function isn't needed.
> I'm not sure if this is sufficient for your use cases, but if I
> could do the this, I would have everything I need:
>
> struct MyInfo { string name; }
> static MyInfo[string] stuff;
>
> class Base {
> static this(this This)() {
> stuff[fullyQualifiedName!This] = MyInfo(This.stringof);
> }
> }
>
> class Derived : Base {
> // static this called for Derived as well
> }
>
> void main(string[] args)
> {
> writeln(stuff["main.Base"].name);
> writeln(stuff["main.Derived"].name);
> }
There's a famous idiom from the C++ world which solves this,
google CRTP...
... or see the quick hack below.
('final' is optional, the interface is also optional...)
interface IBase
{
string Name();
}
class Base(T) : IBase
{
final string Name()
{
return typeof(this).stringof;
}
}
class One : Base!One { }
class Two : Base!Two { }
More information about the Digitalmars-d
mailing list