lambda function with "capture by value"

ikod via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 5 11:54:22 PDT 2017


On Saturday, 5 August 2017 at 18:45:34 UTC, Simon Bürger wrote:
> On Saturday, 5 August 2017 at 18:22:38 UTC, Stefan Koch wrote:
>> [...]
>
> No, sometimes I want i to be the value it has at the time the 
> delegate was defined. My actual usecase was more like this:
>
> 	void delegate()[3] dgs;
> 	for(int i = 0; i < 3; ++i)
> 		dgs[i] = (){writefln("%s", i); };
>
>
> And I want three different delegates, not three times the same. 
> I tried the following:
>
> 	void delegate()[3] dgs;
> 	for(int i = 0; i < 3; ++i)
> 	{
> 		int j = i;
> 		dgs[i] = (){writefln("%s", j); };
> 	}
>
> I thought that 'j' should be considered a new variable each 
> time around, but sadly it doesn't work.

Maybe std.functional.partial can help you.


More information about the Digitalmars-d-learn mailing list