How to dispatch a class function for an object accessed by handle?

wjoe invalid at example.org
Thu Mar 5 19:09:48 UTC 2020


On Thursday, 5 March 2020 at 14:46:24 UTC, Steven Schveighoffer 
wrote:
> On 3/5/20 9:24 AM, wjoe wrote:
>
>> 
>> but how can I call fn in the context of an object instance?
>
> You could do it with delegates. But it's ugly:
>
> import std.stdio;
> class C
> {
>     void foo() { writeln("Yup");}
> }
> void main()
> {
>     alias f = C.foo;
>     auto c = new C;
>     void delegate() dg;
>     dg.funcptr = &f;
>     dg.ptr = cast(void*)c;
>     dg(); // prints "Yup"
> }
>
> I don't know of a way to call f with c aside from this.
>
> -Steve

I have an ugly implementation with a one liner mixin and I don't 
like it. Your solution
looks interesting but I think that's more code than my current 
solution. Thanks for your reply though.


More information about the Digitalmars-d-learn mailing list