Capturing a variable by value?

ZombineDev via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Feb 3 10:09:52 PST 2016


On Wednesday, 3 February 2016 at 18:03:24 UTC, ZombineDev wrote:
> C++11 allows you to capture a local variable explicitly by 
> value.
>
> What is the simplest way to make code below print "0 1 .. 9", 
> like the C++ version does?
>
> D version:
> ```
> import std.stdio;
>
> void main()
> {
>     alias F = void delegate();
> 	
>     F[] arr;
> 	
>     foreach (i; 0 .. 10)
>         arr ~= { write(i, " "); };
> 			
>     foreach (f; arr)
>         f();
> }
> ```
> Prints: 9 9 9 9 9 9 9 9 9 9
>
>
> C++ version:
> ```
> #include <iostream>
> #include <functional>
> #include <vector>
> using namespace std;
>
> int main()
> {
>     using F = function<void()>;
>
>     vector<F> arr;
>
>     for (auto i = 0; i < 10; ++i)
>         arr.push_back([=]() { cout << i << " "; });
>
>     for (auto f : arr)
>         f();
> }
> ```
> Prints: 0 1 2 3 4 5 6 7 8 9
>
> One stupid solution is to replace `0 .. 10` with staticIota!(0, 
> 10), which would unroll the loop at CT, but I want something 
> more general that would me allow me to capture the values of a 
> range while iterating over it at run-time.

I think these two links, more or less, answer my question:
http://stackoverflow.com/questions/29759419/closures-in-loops-capturing-by-reference
https://issues.dlang.org/show_bug.cgi?id=2043


More information about the Digitalmars-d-learn mailing list