Functors

Craig Black craigblack2 at cox.net
Thu Jun 28 11:43:14 PDT 2007


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