Retreive method given object, name and arguments

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 11 13:41:33 PDT 2016


On Thursday, 11 August 2016 at 20:27:51 UTC, Michael Coulombe 
wrote:


import std.stdio;

struct S {
   void foo () { writeln("foo()"); }
   void foo (int n) { writeln("foo(", n, ")"); }
}


auto doit(string methodName, C, Args...) (C c, Args args) {
   static if (is(typeof(mixin("c."~methodName~"(args)")))) {
     mixin("return c."~methodName~"(args);");
   } else {
     throw new Exception("no method '"~methodName~"' in type 
"~C.stringof);
   }
}


void main () {
   S s;
   s.doit!"foo"(42);
   s.doit!"foo"();
   s.doit!"oops"(); // this throws
}


of course, you can replace `static if` with `static assert` to 
turn it into compile-time error.


More information about the Digitalmars-d-learn mailing list