Functors

Nathan Allan nathan at alphora.com
Fri Jun 29 10:29:35 PDT 2007


Isn't the "words" part of the union assuming 32bit pointers?  How about 
using an array of void pointers, or better yet assign both members to null 
before setting either of them.  This is more defensive as it allows future 
versions of D to change the internal representations of delegates and 
function pointers.

Best,

--
Nathan Allan

"Craig Black" <craigblack2 at cox.net> wrote in message 
news:f60vdo$2fb8$1 at digitalmars.com...
>I just realized that a Functor class is much much easier to express in D 
>than in C++.  Functors are more flexible than delegates because they can be 
>associated with static/global functions as well as functions local to a 
>class or struct.  In essense they can be either a function or a delegate. 
>The implementation is also pretty efficient.  The implementation below does 
>not support functions/delegates with return values, but that would be easy 
>to accommodate.  Anyway, thought it might be useful to someone.
>
> struct Functor(A...)
> {
> private:
>
>  union
>  {
>    void function(A) fun;
>    void delegate(A) del;
>    int[2] words;
>  }
>
> public:
>
>  void clear()
>  {
>    words[0] = 0;
>    words[1] = 0;
>  }
>
>  void opAssign(void function(A) arg)
>  {
>    fun = arg;
>    words[1] = 0;
>  }
>
>  void opAssign(void delegate(A) arg)
>  {
>    del = arg;
>  }
>
>  void invoke(A args)
>  {
>    if(words[0] == 0) return;
>    if(words[1] == 0) fun(args);
>    else del(args);
>  }
> }
>
> int main(char[][] args)
> {
>  // A functor that takes no parameters
>  Functor!() functor;
>
>  static void fun() { printf("In static function.\n"); }
>  functor = &fun;
>  functor.invoke;
>
>  struct A { public void fun() { printf("In local function.\n"); } }
>  A a;
>  functor = &a.fun;
>  functor.invoke;
>
>  return 0;
> }
> 




More information about the Digitalmars-d mailing list