lambda function with "capture by value"

Simon Bürger via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 5 12:08:36 PDT 2017


On Saturday, 5 August 2017 at 18:54:22 UTC, ikod wrote:
> 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.

Thanks. But std.functional.partial takes the fixed arguments as 
template parameters, so they must be known at compile-time. 
Anyway, I solved my problem already a while ago by replacing 
delegates with custom structures which overload the 
call-operator. I opened this thread just out of curiosity. Takes 
a couple lines more but works fine.


More information about the Digitalmars-d-learn mailing list