Whitch can replace std::bind/boost::bind ?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Mar 18 10:24:27 PDT 2016


On 03/18/2016 03:50 AM, Dsby wrote:
>
> foreach (i ; 0..4) {
>      auto th = new Thread(delegate(){listRun(i);});//this is erro
>      _thread[i]= th;
>      th.start();
> }
>
> void listRun(int i)
> {
>       writeln("i = ", i); // the value is not(0,1,2,3), it all is 2.
> }
>
>
> I want to know how to use it like std::bind.
>
>

A workaround is an intermediate function that returns the delegate:

import std.stdio;
import core.thread;

void listRun(int i)
{
      writeln("i = ", i); // the value is not(0,1,2,3), it all is 2.
}

auto makeClosure(int i) {
     return delegate(){listRun(i);};
}

void main() {
     Thread[4] _thread;

     foreach (i ; 0..4) {
         auto th = new Thread(makeClosure(i));
         _thread[i]= th;
         th.start();
     }
}

Prints different values:

i = 1
i = 0
i = 2
i = 3

Ali



More information about the Digitalmars-d-learn mailing list