Call different member functions on object sequence with a generic handler function?

Ali Çehreli acehreli at yahoo.com
Fri Jun 29 18:05:00 UTC 2018


On 06/29/2018 09:44 AM, Robert M. Münch wrote:

> So, how can I write a generic handler that does the iteration, where I 
> can specify which member function to call?

Passing a lambda or a string mixin:

import std.stdio;

class C {
     void A() {
         writeln(__FUNCTION__);
     }

     void B() {
         writeln(__FUNCTION__);
     }
}

void handler(alias func)(C[] cs) {
     foreach (c; cs) {
         func(c);
     }
}

void handler_2(string func)(C[] cs) {
     foreach (c; cs) {
         enum expr = "c." ~ func ~ "();";
         mixin(expr);
     }
}

void main() {
     auto cs = [ new C(), new C() ];

     handler!(o => o.A())(cs);
     handler!(o => o.B())(cs);

     handler_2!"A"(cs);
     handler_2!"B"(cs);
}

Ali


More information about the Digitalmars-d-learn mailing list