Calling class methods by pointers

wrzosk dprogr at gmail.com
Mon Nov 22 14:24:32 PST 2010


Is there any way to save pointer to class method, and call it later?

I know about ptr, and funcptr properties of delegates. I tried to change 
ptr and or funcptr manually after delegate was obtained. It worked in 
some situations. I don't know if it is a correct use of delegate:

import std.writeln;

class Foo
{
    string name;
    this(string e)
    {
        name = e;
    }
    void Print()
    {
        writeln("Print on ", name);
    }
    void Print2()
    {
        writeln("Print2 on ", name);
    }

}

auto foo = new Foo("foo");
auto dg = &foo.Print;
auto foo2 = new Foo("foo2");

dg();                        // Print on foo
dg.ptr = foo2;
dg();                        // Print on foo2
dg.funcptr = &Foo.Print2;
dg();                        // Print2 on foo2

The problem i see is that in funcptr there is real entry point for 
method used, not the index in virtual table, so the polymorphism can't 
work with that.

As I have written - i don't know whether it is correct use for delegate. 
Possibly the ptr, funcptr should be both const (Then is it possible to 
call method on object like in C++ ->* or .*?)
If not, then maybe delegates should work a little different.


More information about the Digitalmars-d-learn mailing list