lambda function with "capture by value"

Temtaime via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 5 12:58:08 PDT 2017


On Saturday, 5 August 2017 at 19:19:06 UTC, Simon Bürger wrote:
> On Saturday, 5 August 2017 at 18:54:22 UTC, ikod wrote:
>> Maybe std.functional.partial can help you.
>
> Nope.
>
> 	int i = 1;
> 	alias dg = partial!(writeln, i);
> 	i = 2;
> 	dg();
>
> still prints '2' as it should because 'partial' takes 'i' as a 
> symbol, which is - for this purpose - kinda like "by reference".
>
> Anyway, I solved my problem already a while ago by replacing 
> delegates with custom struct's that implement the 
> call-operator. I started this thread just out of curiosity, 
> because as I see it, the purpose of lambdas is pretty much to 
> remove the need for such custom constructions.

This one works

	void delegate()[3] dgs;
  	for(int i = 0; i < 3; ++i)
  	{
  		(k){ dgs[k] = {writefln("%s", k); }; }(i);
  	}

  	dgs.each!(a => a());


More information about the Digitalmars-d-learn mailing list