Dynamic templated virtuals - I still often want them
Tove
tove at fransson.se
Thu Jul 23 10:31:08 UTC 2020
On Thursday, 23 July 2020 at 10:18:34 UTC, Arafel wrote:
> On 23/7/20 11:51, Tove wrote:
>> It compiles but doesn't work, in your link you compiled with
>> "-c", so the runtime assert was never evalutated.
>
> Ups! Sorry, I feel quite dumb now... I had the `-c` left from
> some previous tests and didn't notice.
>
> I have indeed reviewed my code, and the caller is also
> templated on the actual class, i.e., it's also calling the
> method with the derived type.
>
> And in fact, now that I think about it, it can't possibly work
> at compile time. Consider:
>
> ```
> Base b = uniform(0,2) ? new Base() : new Derived();
> ```
>
> This can obviously not be resolved at compile time (where the
> template `this` parameter works).
>
> For runtime resolution you can already use `typeid(this)`, and
> this (this time yes) works:
>
> ```
> module foo;
>
> import std;
>
> class Base {
> string serialize() {
> return typeid(this).toString; // just for example
> }
> }
>
> class Derived : Base {
>
> }
>
> void main() {
> Base b = new Derived();
> assert(b.serialize == "foo.Derived");
> }
> ```
Yes, this works fine. It has at least two issues though.
1) Slower than a virtual function call, but I suppose the result
of typeid could be cached to mitigate this issue.
2) TypeInfo cannot be used with -betterC
More information about the Digitalmars-d
mailing list