Library writing - delegates or fp's?

Chad J gamerChad at _spamIsBad_gmail.com
Tue Jun 20 21:40:15 PDT 2006


So I have decided to roll my own GUI library, one dedicated to computer 
games.  But I've run into a bit of an unpleasant design problem - for 
handling callbacks, how should my library expose function pointers and 
delegates?

I suppose I could choose one or the other, but I think it desirable to 
allow use of both since I don't want to force the user of the library 
into a particular style or make them use ugly workarounds.  I am 
currently thinking of a few possible solutions, none of which look very 
pleasing to me:

#1:  Force them to use delegates and work around it to do module-level 
programming.  Example -

import std.stdio;

int delegate(int) increment;

void main()
{
     Dummy d = new Dummy();
     increment = &d.classIncr;
     writefln( increment(1) );
}

int incr( int a )
{
     return a + 1;
}

class Dummy
{
     this() {}

     int classIncr( int a )
     {
         return incr(a);
     }
}

#2:  Provide a templated struct kind of thing that can double as a 
function pointer or a delegate, but is kinda clumsy to deal with.  EX:

import std.stdio;

alias CallBack!(int function(int,Object)) IncCallBack;
IncCallBack increment;

void main()
{
     increment.functionPointer = &incr;
     writefln( increment.functionPointer(1,null) );
}

int incr( int a )
{
     return a + 1;
}

struct CallBack( fpType )
{
     Object object = null;
     fpType functionPointer;

     static CallBack!(fpType) opCall( fpType fp )
     {
         CallBack!(fpType) result;
         result.functionPointer = fp;
         return result;
     }
}

#3:  Expose both function pointers and delegates, with some kind of 
naming convention.  I suppose there could be a better naming convention 
here, but it seems hackish as well.  EX:

void delegate(int,int,ubyte) mouseButtonUp_dg;
void function(int,int,ubyte) mouseButtonUp_fp;


Maybe I'm missing something obvious.  I'd appreciate it if someone has a 
better solution than any of these.  Otherwise I'll settle for some wise 
advice from those who have already been here :)



More information about the Digitalmars-d-learn mailing list