On Friday, 29 June 2018 at 16:44:36 UTC, Robert M. Münch wrote:
I hope this is understandable... I have:
class C {
void A();
void B();
void C();
}
I'm iterating over a set of objects of class C like:
foreach(obj; my_selected_objs){
...
}
The iteration and code before/afterwards always looks the same,
I need this iteration for many of the memember functions like
C.A() and C.B(), etc.
foreach(obj; my_selected_objs){
...
obj.A|B|C()
...
}
So, how can I write a generic handler that does the iteration,
where I can specify which member function to call?
void do_A() {
handler(C.A()); ???
}
void do_B() {
handler(C.B()); ???
}
handler(???){
foreach(obj: my_selected_objs){
???
}
}
Viele Grüsse.
Trying to fiddle around a bit with delegates.. But why is the
context for delegates not working for classes??
https://run.dlang.io/is/Rxeukg
import std.stdio;
class Aclass
{
int i;
void foo() { writeln("called ", i); }
}
struct Bstruct
{
int i;
void foo() { writeln("called ", i); }
}
template callFoo(T)
{
alias Dun = void delegate();
void callFoo(T t)
{
Dun fun;
fun.funcptr = &T.foo;
fun.ptr = cast(void*)(&t);
Dun gun;
gun = &t.foo;
writeln(fun.ptr, " (fun.ptr of " ~ T.stringof ~ ")");
writeln(gun.ptr, " (gun.ptr of " ~ T.stringof ~ ")");
writeln(&t, " (Address of instance (context))");
fun();
gun();
}
}
void main()
{
auto a = new Aclass();
a.i = 5;
auto b = Bstruct();
b.i = 7;
writeln("---- Doesn't work ----");
callFoo(a);
writeln("\n---- Works ----");
callFoo(b);
}