Can change vtbl record at runtime ?

frame frame86 at live.com
Wed Feb 3 10:56:51 UTC 2021


On Wednesday, 3 February 2021 at 05:30:37 UTC, Виталий Фадеев 
wrote:
> Reason:
>     Reuse component,
>     bind custom callback without creating new class.
>
> Concept example:
>     class SaveFilePopup
>     {
>         void onSuccess() { /* default operations */ }
>     }
>
>     auto saveFile = new SaveFilePopup();
>     saveFile.onSuccess = { /* New operations */ }
>
> Delegate:
>     may be... but, for speed reason, is possible to set the 
> default code at compile-time ?
>
>     class X
>     {
>        void delegate() onSuccess = { /* default code */ };
>     }
>
> Context:
>     GUI, components, callbacks
>
> Possible to change the vtbl record at runtime ?
> Has functional for update vtbl records ?

It is possible to change to context of a delegate:

class A {
     int x = 10;
     void foo() {
         writeln(x);
     }
}

class B {
     int x = 20;
}

void main() {
     auto a = new A;
     auto b = new B;

     auto fn = &a.foo;
     fn();

     fn.ptr = &b.__vptr;
     fn();
}

But this is maybe not the best practice. If you just do not want 
to repeat yourself for identical code each class, use a mixin 
template for it.


More information about the Digitalmars-d-learn mailing list