On Tuesday, 27 October 2015 at 07:52:27 UTC, Jacob Carlborg wrote:
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.
It's not a template function. The auto override wouldn't be
instantiated if/when it's called. It would always be instantiated
automatically when the class was compiled. Then, if you were just
using the class as an import, the compiler would know that the
definition should exists somewhere(static lib, etc..).
When an auto override function was called, it may or may not have
the definition..it wouldn't matter, since it's like a virtual
function. But, if someone tried to subclass a class which had
even one auto override function with missing it's definition,
then the effect would be the same as trying to subclass a
sealed/final class.
Bit