www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Calling class methods by pointers

reply wrzosk <dprogr gmail.com> writes:
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.
Nov 22 2010
parent reply Jesse Phillips <jessekphillips+D gmail.com> writes:
wrzosk Wrote:

 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.
You would want something like: dg(); // Print on foo dg = &foo2.Print; dg(); // Print on foo2 dg = &foo2.Print2; dg(); // Print2 on foo2
Nov 22 2010
parent wrzosk <dprogr gmail.com> writes:
On 23.11.2010 01:22, Jesse Phillips wrote:
 wrzosk Wrote:

 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.
You would want something like: dg(); // Print on foo dg =&foo2.Print; dg(); // Print on foo2 dg =&foo2.Print2; dg(); // Print2 on foo2
That's obvious to me how to use is. But what is the purpose of read write ptr and funcptr ?
Nov 22 2010