Dynamic templated virtuals - I still often want them

Arafel er.krali at gmail.com
Thu Jul 23 08:46:54 UTC 2020


On 23/7/20 4:38, Adam D. Ruppe wrote:
> 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`.

This does work today, you just don't need the `virtual` keyword:

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

class Derived : Base {

}

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

https://run.dlang.io/is/vp1koK

I have used this to do some nice tricks. What is missing is to make the 
`this` parameter work out of normal function, so with static functions, 
and even out of functions:

https://issues.dlang.org/show_bug.cgi?id=10488
https://issues.dlang.org/show_bug.cgi?id=20277

Specifically, I want to be able to transform Compile-time introspection 
into run-time instrospection:

```

TypeInfo_Class[string] rtIntrospection;

class Base {
	shared static this (this This) {
		rtIntrospection[This.stringof] = This.classinfo;
	}
}

class Derived : Base { } // The entry is added automatically
```

Now if you want to have something like this you have to depend on the 
end user registering each class manually.


More information about the Digitalmars-d mailing list