On Thu, Jul 23, 2020 at 12:40 PM Adam D. Ruppe via Digitalmars-d <digitalmars-d@puremagic.com> wrote:
You might know about D's template this parameters, which adapt to
the static type of a `this` reference on a call, or with the
curiously recurring template pattern, which passes a derived
class to the base class so the base class can inspect the derived
class.

Both of these are useful at times, but neither quite do what I
have in mind here.

Imagine this:

---
class Base {
      virtual string serialize(this This)() {
            return This.stringof; // just for example
      }
}

class Derived : Base {

}

void main() {
     Base b = new Derived();
     assert(b.serialize() == "Derived");
}
---

That does NOT work today. For one, of course, D has no `virtual`
keyword, but if you left that out, it would compile, but fail the
assert because the static type of `b` passed to the template This
is actually still `Base`.

But imagine if `serialize` actually got a virtual table entry,
just like if it wasn't a template at all, but each child class
automatically got an instance of it made for itself.

So it would be as if I wrote

class Base {
      string serialize() {
            return Base.stringof;
      }
}

class Derived : Base {
      override string serialize() {
            return Derived.stringof;
      }
}

by hand. Of course, it is possible to do this kind of thing with
mixin templates or the CRTP, but in both cases, the Derived class
must actually write it in the child class, and if you don't
there's no way to really tell; it will still compile and just use
the base class implementation. Which might be OK but it isn't
perfect.

It would just be cool if the base class template was
automatically instantiated again for the child class, while still
working like a normal virtual call.

That's clever, and I wish I had have thought of it before!!
This pattern would have helped me in multiple scenarios I've encountered in the past where I had to deploy awkward and ugly mixin tricks.