Getting the address of a member function at compile time inside a member function
Steven Schveighoffer
schveiguy at gmail.com
Mon Jul 14 01:53:21 UTC 2025
On Sunday, 13 July 2025 at 02:53:24 UTC, Walter Bright wrote:
> On 7/6/2025 8:28 PM, Steven Schveighoffer wrote:
>> It seems the act of being in a member function engages the
>> compiler to try and add a context pointer. And there's no way
>> to turn this off, except to not be in a member function.
>
> But non-static member functions must have a context pointer!
> It's the whole point.
In general, this function pointer is still a valid function
pointer, and there is value to accessing the pointer. e.g.
`assert(dg.funcptr == &S.foo);`
Note, you can use function pointers to build delegates:
```d
import std.stdio;
import std.random;
struct S
{
void foo() { writeln("foo"); }
void bar() { writeln("bar"); }
}
void main()
{
void function()[] fns = [&S.foo, &S.bar];
void delegate() dg;
S s;
dg.ptr = &s;
dg.funcptr = fns[uniform(0, 2)];
dg();
}
```
I would be excited if D could improve on this. Perhaps by
allowing a type like `void function(ref S this)`, which actually
could be called with an `S`. It could also make delegate types
more useful and safer.
-Steve
More information about the Digitalmars-d
mailing list