Pointer to method C++ style

Sergey Gromov snake.scaly at gmail.com
Fri Jul 24 07:31:38 PDT 2009


Fri, 24 Jul 2009 09:07:30 -0400, Steven Schveighoffer wrote:

> On Thu, 23 Jul 2009 22:09:12 -0400, Sergey Gromov <snake.scaly at gmail.com>  
> wrote:
> 
>> Thu, 23 Jul 2009 11:54:40 -0400, Steven Schveighoffer wrote:
>>
>>>          LOOKUP_TABLE[0] = Method("method1", &Component.method1);
>>>          LOOKUP_TABLE[1] = Method("method2", &Component.method2);
>>
>> These two lines are weird.  ``pragma(msg)`` shows that type of
>> ``&method1`` is ``void function()`` while it must be ``void delegate()``
>> for a non-static member because of difference in calling convention.
>> Actually I think that taking an address of a non-static member in a
>> static context must be a compile time error.
> 
> It's because I'm taking the address of the function on the type, not on an  
> instance.  It's not a delegate because there's no "this" pointer yet.
> 
> It makes sense to me anyways.  A delegate is a normal function pointer  
> coupled with a hidden context parameter.

The ``Type.`` part does not change anything.  It simply directs compiler
to use overloads from a particular class hierarchy level.   Here:

    static Method[] LOOKUP_TABLE2 = [
        { name : "method1", method : &Component.method1 },
        { name : "method2", method : &method2 }
    ];

This code compiled with DMD 1.046 gives the following errors:

    test2.d(30): Error: non-constant expression & method1
    test2.d(30): Error: non-constant expression & method2

Also if you add this code:

    pragma(msg, "outside: " ~ typeof(&method1).stringof);
    void method1() { writefln("method1");
        pragma(msg, "inmeth: " ~ typeof(&method1).stringof);
    }

you get:

    outside: void function()
    inmeth: void delegate()

So the type of a non-static method address taken in a static context is
obviously wrong.


More information about the Digitalmars-d-learn mailing list