store template value

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 2 12:21:43 PDT 2015


On 08/02/2015 05:15 AM, maarten van damme via Digitalmars-d-learn wrote:

 > Oh, neat. This saves the day :)

Awesome! :) However, that solution depends on the implementation details 
of std.parallelism. It is possible to do the same thing by inheriting 
from an 'interface' and "hiding" the templated type under there.

The following program need not spell out the template instance:

import std.parallelism;

double foo(int i)
{
     return i * 1.5;
}

double bar(int i)
{
     return i * 2.5;
}

/* This is what the user code will need to know about. */
interface MyTask
{
     void executeInNewThread();
     void yieldForce();
}

/* This subclass hides the actual templated Task type. */
class MyTaskImpl(TaskType) : MyTask
{
     TaskType t;

     this(TaskType t)
     {
         this.t = t;
     }

     /* These two are to satisfy the interface requirements. */
     void executeInNewThread()
     {
         t.executeInNewThread();
     }

     void yieldForce()
     {
         t.yieldForce();
     }
}

/* A convenience function to hide the Task template instance. */
auto newMyTask(TaskType)(TaskType taskObject)
{
     return new MyTaskImpl!TaskType(taskObject);
}

void main()
{
     /* Populate */
     MyTask[] myTasks;
     myTasks ~= newMyTask(task!foo(1));
     myTasks ~= newMyTask(task!bar(2));

     import std.algorithm;

     /* Execute */
     myTasks.each!(t => t.executeInNewThread);

     /* Wait */
     myTasks.each!(t => t.yieldForce);
}

Ali



More information about the Digitalmars-d-learn mailing list