Automatic method overriding in sub-classes

Jacob Carlborg via Digitalmars-d digitalmars-d at puremagic.com
Tue Oct 27 00:52:26 PDT 2015


On 2015-10-27 00:25, Tofu Ninja wrote:
> I know this has basically no chance of ever actually being added because
> that is the way of all "I want feature X" threads, but I thought I would
> post this anyways because I seem to want it constantly.
>
> So we have TemplateThisParameters methods which are cool but have some
> drawbacks.
> They are templates so they are implicitly non-virtual and are called
> based on the type of the reference.
> It would be very nice to be able to auto generate method overrides based
> on the this type with out having to drop a mixin in every sub class.
> This would be very useful for CT-reflection.
> I will call this new feature auto override methods for the rest of this
> post.
>
> An auto override method would take the form of a template method with
> only a single type argument that is the type of the class or any of it's
> sub classes.
> To differentiate it from TemplateThisParameters it could look like:
>
>       returnType functionName(auto override this T)() {...}
>
> When ever a class with an auto override method is sub-classed, the auto
> override method template is re-instantiated with the sub-class type and
> the method is overridden automatically.
> Key point is that the method will still be virtual.
>
>
> Here is an example contrasting an auto override method with a regular
> TemplateThisParameters method.
>
> ##################################
> class A
> {
>       void foo(this T)() { writeln(T.stringof); }
>       void bar(auto override this T)() { writeln(T.stringof); }
> }
>
> class B : A {}
>
> void main()
> {
>       A a = new A();
>       a.foo(); // prints "A"
>       a.bar(); // prints "A"
>
>       B b = new B();
>       b.foo(); // prints "B"
>       b.bar(); // prints "B"
>
>       A c = new B();
>       c.foo(); // prints "A"
>       c.bar(); // prints "B" <-- main advantage, method is virtual
> }
> ##################################

I don't think this is possible. Think of code looking like this:

// Imagine not having access to the source code "createA"
A createA()
{
     new B;
}

void inspectA(A a)
{
     a.bar();
}

How should the compiler know that when instantiating/calling "bar", T 
should be set to B? The compiler might not even know about B exists at 
all. Even if the compiler does have access to the complete source code 
it would, most likely, need to do a full program analyze to figure out 
the type of T, which is quite complicated.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list