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

Steven Schveighoffer schveiguy at gmail.com
Sun Jul 6 01:10:16 UTC 2025


In discord, a user had the following puzzle:

```d
struct S
{
    void foo() {}
    void bar() {
        static void function() fn = &foo;
    }
}
```

This does not compile. The compiler says it cannot resolve the 
`this` pointer at compile time.

Fine, so let's try naming the type!

```d
static void function() fn = &S.foo;
```

Nope, `S` is just a namespace at this point.

What about just asking for the `funcptr`?


```d
static void funciont() fn = &foo.funcptr;
```

Nope, still the same error. I tried some other stuff, and it also 
told me it cannot evaluate `funcptr` at compile time.

I found the following workaround works, but it's not very nice 
that you have to do this:

```d
enum fnptr(alias fn) = &fn;

static void function() fn = fnptr!foo;
```

Now, it just gets the function pointer.

Does anyone have a solution to this that does not involve a 
workaround that requires writing a helper thing? It appears there 
is no way to tell the compiler you don't want the context pointer.

-Steve


More information about the Digitalmars-d mailing list