virtual method pointer

jerro a at a.com
Fri May 4 02:30:40 PDT 2012


On Thursday, 3 May 2012 at 18:47:11 UTC, Gor Gyolchanyan wrote:
> I need to get a pointer to a virtual method, which is in turn a
> function pointer, being set by virtual method binding.
> Can anyone, please, tell me how to get it? Taking the delegate 
> of the
> method won't do, because I need it to behave exactly as a 
> virtual
> method call, except I pass the "this" explicitly.
> I need this in an event handling mechanism I'm making. You 
> derive from
> the Sink class, passing your static type to the constructor, 
> which
> scans your virtual methods, that conform to specific 
> requirements and
> extracts them into an array, which later uses to dispatch the 
> incoming
> events.
> It will feel much like a run-time virtual template method.

If I understand you correctly, you could use something like this

template methodToFunction(A, string method)
{
      auto methodToFunction(A a, ParameterTypeTuple!(mixin("A." ~ 
method)) p)
      {
          return mixin("&a." ~ method)(p);
      }
}

If you use it like this:

class Foo
{
     int m;

     void bar(int a, string b)
     {
         writefln("%s\t%s\t%s", m, a, b);
     }
}

class Child: Foo
{
     void bar(int a, string b)
     {
         writeln("child");
     }
}

void main()
{
     auto foo = new Foo;
     foo.m = 1;
     auto child = new Child;
     auto bar = &methodToFunction!(Foo, "bar");
     bar(foo, 2, "3");
     bar(child, 2, "3");
}

It prints:

1	2	3
child

It won't work correctly with overloading, though. It could
be made to work with overloading, but then you would
have to pass all the parameter types of the method to
the methodToFunction template.


More information about the Digitalmars-d mailing list