Capturing a variable by value?

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


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.


More information about the Digitalmars-d-learn mailing list