Given an object, how to call an alias to a member function on it?

ag0aep6g anonymous at example.com
Tue May 2 13:06:41 UTC 2023


On 02.05.23 14:52, Quirin Schroll wrote:
> How do I invoke the member function in a reliable way? Given `obj` of 
> the type of the object, I used `mixin("obj.", __traits(identifier, 
> memberFunc), "(params)")`, but that has issues, among probably others, 
> definitely with visibility. (The member function alias is a template 
> parameter.)

Construct a delegate from the alias and the object, and call that delegate:

----
class C
{
     int field = 42;
     void method() { import std.stdio; writeln(field); }
}

void fun(alias method)(C c)
{
     void delegate() dg;
     dg.funcptr = &method;
     dg.ptr = cast(void*) c;
     dg();
}

void main()
{
     fun!(C.method)(new C); /* prints "42" */
}
----


More information about the Digitalmars-d-learn mailing list