I implemented delegates in D
Alex Parrill via Digitalmars-d
digitalmars-d at puremagic.com
Thu Jun 9 14:32:33 PDT 2016
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)
More information about the Digitalmars-d
mailing list