Library writing - delegates or fp's?
Derek Parnell
derek at nomail.afraid.org
Tue Jun 20 22:33:53 PDT 2006
On Wed, 21 Jun 2006 00:40:15 -0400, Chad J wrote:
> 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 -
It doesn't have to be as complex as that. All you need to do to turn
module-level functions into delegates is to place them inside the module's
constructor or any other function for that matter, including main(). For
example ..
import std.stdio;
int delegate(int) increment;
static this()
{
int incr( int a )
{
return a + 1;
}
increment = &incr;
}
void main()
{
writefln( increment(1) );
}
Or if you prefer the new function literal syntax (and not use the module
constructor) ...
import std.stdio;
int delegate(int) increment;
int delegate(int) decrement;
void Init_Delegates()
{
increment = delegate int ( int a )
{
return a + 1;
};
decrement = delegate int ( int a )
{
return a - 1;
};
}
void main()
{
Init_Delegates();
writefln( increment(1) );
writefln( decrement(1) );
}
--
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
21/06/2006 3:18:11 PM
More information about the Digitalmars-d-learn
mailing list