Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D Analogue to C++ member-function-pointers, not necessarily delegates

I have been learning D, and am in particular very excited for it's Generic programming capabilities. Delegates are wonderful, and apparently they have completely replaced member-function-pointers, so I was 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 have learned of function pointers and delegates in D, is that neither of them can do this, since function pointers can only be declared for global functions, and delegates have to be bound to an object, there is no "partial delegate" that I can find. As seen here, I cannot use a delegate, since there is no single object that can be bound to the method that is to be called.

I know that I could do it with mixins, and essentially make it a macro. However this really doesn't sound D-like, and I figured there should be "The correct way"

like image 525
Ramon Zarazua B. Avatar asked Nov 08 '11 08:11

Ramon Zarazua B.


1 Answers

You could still use a 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

like image 116
kennytm Avatar answered Sep 22 '22 00:09

kennytm