Getting the address of a member function at compile time inside a member function

Steven Schveighoffer schveiguy at gmail.com
Mon Jul 7 03:28:58 UTC 2025


On Sunday, 6 July 2025 at 03:47:07 UTC, Walter Bright wrote:
> When taking the address of a member function, a delegate is 
> created, not a function pointer. The delegate is comprised of 
> two members: a function pointer, and a context pointer (i.e. 
> `this`). When the static fn is initialized, there is no `this` 
> available at compile time, so it (correctly) fails to compile.

That is not what happens when outside a member function. I should 
have been more descriptive.

```d
void function() fn = &S.bar; // ok!
struct S {
    void bar() {}
    static void function() fn = &bar; // ok!
    void foo() {
        static x() => &bar;
        static void function() fn = x(); // ok!

        enum fnptr(alias fn) = &fn;
        static void function() fn2 = fnptr!bar; // ok!

        // these all error
        // static void function() fn3 = &bar;
        // static void function() fn4 = &S.bar;
        // static void function() fn5 = (&bar).funcptr;
    }
}
```

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.

>
> The workaround you figured out is pretty clever! I don't think 
> you'll be able to do better.

Probably. But it does seem odd to have to jump through this hoop.

-Steve


More information about the Digitalmars-d mailing list