I implemented delegates in D

Mathias Lang via Digitalmars-d digitalmars-d at puremagic.com
Thu Jun 9 15:06:24 PDT 2016


To avoid the delegate being GC allocated, use `scope foo = (int i) { ... }`
at call site.
You can also make your function signature as `void func(scope void
delegate() dg)` in which case it won't allocate if you pass a literal
directly.

2016-06-09 23:57 GMT+02:00 maik klein via Digitalmars-d <
digitalmars-d at puremagic.com>:

> On Thursday, 9 June 2016 at 21:32:33 UTC, Alex Parrill wrote:
>
>> On Thursday, 9 June 2016 at 21:02:26 UTC, maik klein wrote:
>>
>>> Has this been done before?
>>>
>>
>> Well, yes, the entire point of delegates is to be able to capture
>> variables (as opposed to function pointers, which cannot).
>>
>>
>> auto createADelegate(int captured) {
>>         return (int a) => captured + a;
>> }
>>
>> void main() {
>>         auto dg1 = createADelegate(5);
>>         auto dg2 = createADelegate(32);
>>         assert(dg1(5) == 10);
>>         assert(dg1(10) == 15);
>>         assert(dg2(8) == 40);
>>         assert(dg2(32) == 64);
>> }
>>
>> https://dpaste.dzfl.pl/90ebc29651f6
>>
>> (Unfortunately template delegates, like the ones used with map, don't
>> keep their captured variables alive after the captured variables go out of
>> scope, but it doesn't sound like you need those)
>>
>
> I meant, "has this been implement as a library before". I am well aware
> that delegates exist in the language but as far as I know you can not do
> manual allocation with delegates (to avoid the GC).
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20160610/3d6d8696/attachment-0001.html>


More information about the Digitalmars-d mailing list