opDispatch() is pretty damn great

Szymon Gatner noemail at gmail.com
Wed Jan 8 15:20:04 PST 2014


Still exploring what D has to offer but this blew my mind:

import std.stdio;

struct Base
{
   void print(string text)
   {
     writeln("Base : " ~ text);
   }
   int add(int a, int b)
   {
     return a + b;
   }
}

struct Wrap
{
   auto opDispatch(string op, Args...)(Args args)
   {
     enum name = op;
     return __traits(getMember, base, name)(args);
   }
   Base base;
}

int main(string[] argv)
{
   Wrap wrap;
   wrap.print("wrapped call, magic!");
   auto res = wrap.add(1, 5);
   return 0;
}

I don't quite understand why "enum name" part is necessary (as my 
understanding is that "op" is compile-time constant anyway) but 
since I am crap at D that is what worked for me. I was thinking 
for log time how great something like that would be in C++ and I 
just tried this id D... Mind blown... std::reference_wrapper<> 
would be a zillion times more usable with equivalent of 
opDispatch() this powerful.


More information about the Digitalmars-d-learn mailing list