How to get address of a nested function?

Daniel Kozak kozzi11 at gmail.com
Tue Nov 10 20:13:30 UTC 2020


On Tue, Nov 10, 2020 at 11:55 AM Max Samukha via Digitalmars-d-learn <
digitalmars-d-learn at puremagic.com> wrote:

> We can get the compile time equivalent of a member function's
> address by applying '&' to the function in a static context:
>
> struct S {
>      void foo() {}
> }
>
> enum pfoo = &S.foo; // ok
>
> void main() {
>      // now we can use the pointer to create, for example, a
> delegate
>      S s;
>      void delegate() dg;
>      dg.ptr = &s;
>      dg.funcptr = pfoo;
>      dg();
> }
>
> However, we can't do that to a nested function:
>
> void main() {
>      void foo() {
>      }
>      enum pfoo = &foo; // weird kind of an enum delegate;
> pfoo.funcptr can't be accessed at compile time.
> }
>
> Is there a way to get a pointer to a non-static nested function?
>

non static nested function is a delegate, so you can just assign it to
delegate like I have posted or you can du this:

import std.stdio;
void main() {
    void foo() {
        writeln("It works as expected");
    }
    enum pfoo = &foo;

    void delegate() dg;
    dg.ptr = pfoo.ptr;
    dg.funcptr = pfoo.funcptr;
    dg();
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20201110/22ca2d33/attachment.htm>


More information about the Digitalmars-d-learn mailing list