Problem with closures
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Fri Jan 12 06:35:43 PST 2007
Bradley Smith wrote:
> Nevermind. I figured it out. The following works.
>
> import std.stdio;
>
> alias int delegate(int n) AddFunc;
>
> template addN(int N) {
> AddFunc addN() {
> return delegate int (int i) { return i + N; };
> }
> }
>
> void apply (int[] array, AddFunc func) {
> foreach (inout i; array) {
> i = func(i);
> }
> }
>
> void main () {
> int[] numbers = [1,2,3] ;
> writefln("numbers before = ", numbers);
> apply(numbers, addN!(40));
> writefln("numbers after = ", numbers);
> }
>
> Bradley Smith wrote:
>> Using DMD 1.0, I get errors on the template.
>>
>> closureWithTemplate.d(19): delegate
>> closureWithTemplate.TAddN!(40).__dgliteral2 is a nested function and
>> cannot be accessed from main
>> closureWithTemplate.d(6): Error: non-constant expression __dgliteral2
>>
>>
>> Bradley
>>
>> Chris Nicholson-Sauls wrote:
>>> import std .stdio ;
>>>
>>> alias int delegate(int n) AddFunc;
>>>
>>> template TAddN (int N) {
>>> const TAddN = (int i) { return i + N; } ;
>>> }
>>>
>>> void apply (int[] array, AddFunc func) {
>>> foreach (inout i; array) {
>>> i = func(i);
>>> }
>>> }
>>>
>>> void main () {
>>> int[] numbers = [1,2,3] ;
>>>
>>> writefln("numbers before = ", numbers);
>>> apply(numbers, TAddN!(40));
>>> writefln("numbers after = ", numbers);
>>> }
Now that, actually, I consider possibly a bug. But a least the workaround was simple
enough (and small enough to be inlined).
-- Chris Nicholson-Sauls
More information about the Digitalmars-d-learn
mailing list