Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass type information through templates to instantiate objects within in D

How would one pass type information into a thread, so objects of the correct types could be created in the thread using the passed info? Something like this:

struct Test // or class Test
{
  int x, y, z;
}

void testInThread(F, T ...)(T args)
{
  auto obj = F(args);
  // Do stuf with obj in the new thread
}

auto tid = std.concurrency.spawn!(testInThread, Test, 1, 2, 3);

// Threads and stuff...

This doesn't compile, but I'm sure something like this should be possible. I think there's just something I'm not understanding about template parameters.

like image 453
SethSR Avatar asked Feb 13 '23 18:02

SethSR


1 Answers

This line here would compile:

    auto tid = std.concurrency.spawn(&testInThread!(Test, int, int, int), 1, 2, 3);

I'm not sure if you can make it prettier with implicit deduction of those ints or not though. But the reason this compiles is that spawn expects a function. testInThread is a template that generates a function. If you pass it the compile time argument list over there without a runtime list, you can get the address to the function... which is good enough for spawn.

like image 66
Adam D. Ruppe Avatar answered May 12 '23 13:05

Adam D. Ruppe