recursive delegate declaration

BCS BCS at pathlink.com
Tue Jun 20 16:08:31 PDT 2006


kris wrote:
> I have a situation whereby a delegate should return an instance of 
> itself, to enable call chaining. Here's my attempt, which compiles and 
> appears to work with dmd 161:
> 
> --------------
> alias Consume delegate(char[]) Bar;
> typedef Bar delegate (char[]) Consume;
> 
> 
> void main ()
> {
>    Bar consumer (char[] v)
>    {
>         return cast(Bar) &consumer;
>    }
> 
>    emit (&consumer);
> }
> --------------
> 
> The above seems like a tad too much of a hack. Can anyone come up with a 
> cleaner approach?
> 

That's better than what I used. I was using it for a state machine.

State at = Seed;
while(null !is at)
	at = at();

and used something like this:

#struct foo
#{
#	foo delegate(char[]) bar;
#	static foo opCall(foo delegate(char[]) b)
#	{
#		foo ret;
#		ret.bar = b;
#		return ret;
#	}
#}
#
# void emit (foo consume)
# {
#     consume ("1").bar("2").bar("3").bar("4");
# }
#
#void main ()
#{
#   foo consumer (char[] v)
#   {
#        return cast() &consumer;
#   }
#
#   emit foo(&consumer);
#}


If function can be made to work, cast through void* gets it done.



More information about the Digitalmars-d mailing list