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.

Reply via email to