D Analog with C ++ Member-Function pointers, optional delegates

I am learning D, and I am especially excited for it. General programming features. The delegates are wonderful, and apparently they completely replaced the member-member-function pointers, so I got stuck when I wanted to implement something like the following:

template <typename T> void DispatchMethodForAll(std::vector<T*> & container, void (T::* func)(void)) { for(typename std::vector<T*>::iterator it = container.begin(); it != container.end(); ++it) (*it)->*func(); } 

According to what I learned about function pointers and delegates in D, is that none of them can do this, because pointers to objects can only be declared for global functions, and delegates must be bound to an object, there is no "partial delegate" that I can find. As you can see here, I cannot use a delegate, because there is no single object that can be bound to a method that needs to be called.

I know that I could do this with mixins and essentially make it a macro. However, it really doesnโ€™t look like D-like, and I decided that there should be a โ€œright wayโ€

+7
source share
2 answers

You can still use the delegate here.

 void DispatchMethodForAll(T)(T*[] container, void delegate(T*) action) { foreach (it; container) action(it); } ... DispatchMethodForAll(container, (Foo* foo) { foo.func(); }); 

Example: http://www.ideone.com/9HUJa

+6
source

you can extract the page from std.algorithm to find out how it does it

 void DispatchMethodForAll(alias func, T)(T container) { alias unaryFun!func _func foreach (it; container) _func(it); } 

a btw delegate can be bound to a structure, and the compiler can create a custom structure from local (stack distributed) variables and define a delegate on this

this is happening with

 void foo(){ int[] array; int i=0; void bar(int a){ i+=a; } void DispatchMethodForAll(&bar)(array); writeln(i);//prints the sum of array } 

bar is a delegate associated with a structure with (at least) member i type int , local variable i is an alias

+3
source

All Articles