Automatic method overriding in sub-classes
Tofu Ninja via Digitalmars-d
digitalmars-d at puremagic.com
Mon Oct 26 16:25:42 PDT 2015
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
}
##################################
Possible uses:
-Automatic generation of nice toString.
-Auto-generate property panes. This is actually a use I need
right now, to generate property panes for entity types in a game
engine(unity style).
-Another time I needed it, I have a UI system that will
automatically apply ui formatting based on the existence of
"stylize properties" that can be read at compile time, but it
required a virtual method to have to be redefined for each
sub-class which simply reflected on the this type and checked for
the existence of the "stylize properties".
-Check if a sub-class implements certain features
-Check if sub-class has a certain UDA
etc...
I find myself needing this a lot in my code, especially as I
write a lot of CT-reflection.
So far the only way I have found to achieve this is to drop a
string mixin in every subclass putting the override in.
Thoughts?
Any one else needed this before?
Any clever way to do this now that I have not thought of?
-Tofu
More information about the Digitalmars-d
mailing list