Pointer to method C++ style

Sergey Gromov snake.scaly at gmail.com
Thu Jul 23 08:26:18 PDT 2009


Thu, 23 Jul 2009 04:11:14 +0000 (UTC), BCS wrote:

> Hello Sergey,
> 
>> Is there a way to declare and statically initialize some sort of
>> pointer to method, and later call it for an actual object instance?
>> 
> 
> dosn't work but might point you in the right direction:
> 
> template Pn2Fn(R, char[] method)
> {
>      ReturnTypeOf!(mixin("R." ~ method)) Pn2Fn(R r, ArgsOf!(mixin("R." ~ 
> method)) args)
>      {
>           return mixin("r."~method~"(args);");
>      }
> 
> }

Thanks for the advice.  The following code actually works:

import std.stdio;

struct Handler(T)
{
  string name;
  void function(T instance) handler;
}

class A
{
  void method1() { writefln("method1"); }
  void method2() { writefln("method2"); }

  void call(int i)
  {
    LOOKUP_TABLE[i].handler(this);
  }

private:

  static Handler!(A)[] LOOKUP_TABLE =
  [
    { "method1", &callMethod!("method1") },
    { "method2", &callMethod!("method2") }
  ];

  static void callMethod(string name)(A instance)
  {
    mixin("instance." ~ name ~ "();");
  }
}

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


More information about the Digitalmars-d-learn mailing list