On Wed, 22 Jul 2009 23:47:30 -0400, Sergey Gromov <snake.sc...@gmail.com> wrote:

Is there a way to declare and statically initialize some sort of pointer
to method, and later call it for an actual object instance?

I don't know why the "non constant expression error" happens, but constructing a delegate from function pointers is pretty simple:

import tango.io.Stdout;

struct Method
{
    char[] name;
    void function() method;
}

class Component
{
    void method1() {Stdout("method1").newline;}
    void method2() {Stdout("method2").newline;}


// this works, but not sure why I couldn't initialize via a simple array assign...
    static Method[] LOOKUP_TABLE;
    static this()
    {
        LOOKUP_TABLE = new Method[2];
        LOOKUP_TABLE[0] = Method("method1", &Component.method1);
        LOOKUP_TABLE[1] = Method("method2", &Component.method2);
    }

    void call(int i)
    {
        // construct a delegate to call
        void delegate() dg;
        dg.ptr = cast(void*)this;
        dg.funcptr = LOOKUP_TABLE[i].method;
        // call the delegate
        dg();
    }
}

void main()
{
    Component a = new Component;
    a.call(0);
    a.call(1);
}

-------
outputs:

method1
method2

-Steve

Reply via email to