Suggestion: "new delegate" - delegates useable outside of the nesting function scope
Jarrett Billingsley
kb3ctd2 at yahoo.com
Fri Jun 2 17:35:36 PDT 2006
"Burton Radons" <burton-radons at smocky.com> wrote in message
news:e5qkhd$2a1u$1 at digitaldaemon.com...
>I use delegates a lot but the fact that they can only live until the end of
>the nesting function scope means I need to use classes in many cases, which
>is a lot more typing (and fluff telling the autodoc that it's not part of
>the public API, and other problems) when it could be easily fixed. The
>syntax change would be very simple:
>
> dispatcher.add (new delegate void (Event event) { ... });
>
> And the effect would be simple as well: duplicate the calling context's
> stack to the extent that the delegate can see it and use the duplicated
> pointer as the "this" pointer; otherwise it's a regular nested delegate.
> Five minutes work max, very topical changes, explicit allocation, big
> benefits. Is good!
Haha, funny thing is, I'm implementing this _exact_ feature with virtually
the same syntax in a small D-like scripting language I'm writing, although I
use 'function' instead of 'delegate' (as there is no distinction between the
two in my language).
This feature is called "static closures," and is very useful indeed. D's
dynamic closures (that is, the context for the nested function exists as
long as its owning function doesn't return) are fairly useful, but have the
one major downside which you point out.
Implementing static closures in D would be an interesting proposition, as
they would technically be objects, though implicitly. Then there's the
problem with RAII class references. Consider something like:
char delegate() createFileReader(char[] fileName)
{
auto File f = new File(fileName, FileMode.In);
return new delegate char()
{
return f.getc();
};
}
This function would return a function that would be used to read (very
simply) a file, one character at a time. The problem is that the File
reference in the enclosing scope could not be deleted when createFileReader
returns. I suppose the way around this would be to disallow using RAII
class references inside static closures, but..
More information about the Digitalmars-d
mailing list