Problem with closures: Problem solved
Alain
alainpoint at yahoo.fr
Thu Jan 11 07:28:12 PST 2007
David Medlock Wrote:
> D doesn't support true closures, just delegates. Local variables in
> functions are still allocated on the stack and therefore invalid after
> you return from them.
>
> You must use objects for this purpose.
>
> -DavidM
Thank you for the suggestion. I post hereunder my solution to the problem.
import std.stdio;
class ClassClosure
{
this(int n) { num = n;}
private uint num;
int opCall(int x) {return num+x;}
}
void capply(int[] array, ClassClosure func) {
foreach (inout int i; array) { i = func(i); }
}
int main() {
int[] numbers = [1,2,3];
writefln("numbers before=",numbers);
ClassClosure myclosure= new ClassClosure(40);
capply(numbers, myclosure); // add 40 to each number
writefln("numbers after=",numbers);
return 0;
}
Alain
More information about the Digitalmars-d-learn
mailing list