Passing function(whose parameter would be dynamic and the type is unknown) as a parameter to another function.

vino.B bheeman.vino at hotmail.com
Sun Jul 8 18:46:31 UTC 2018


Hi All,

  Request you help, in the below code we pass the function 
"Testfun" as a parameter to another function "process" in order 
for the function "process" to work we have to specify the type of 
the parameter that is passed to the function "(T function(string, 
int) coRoutine, string Test, int Size) ", so now how do we pass a 
function whose parameter would be dynamic and the type is unknown.

void process(T)(T function(string, int) coRoutine, string Test, 
int Size) {
alias scRType = typeof(coRoutine(string.init, int.init));

Eg:

Run1 : process(&Testfun, Test, Size);
void process(T ...)(T function(string, int) coRoutine, string 
Test) {
alias scRType = typeof(coRoutine(string.init, int.init));


Run2 : process(&Testfun, Test, Size, Str1);
void process(T)(T function(string, int, string) coRoutine, string 
Test, int Size, string Str1) {
alias scRType = typeof(coRoutine(string.init, int.init, 
string.int));


Run3 : process(&Testfun, Test);
void process(T)(T function(string, string) coRoutine, string 
Test, int Size) {
alias scRType = typeof(coRoutine(string.init));
PFresult.get = coRoutine(args);

Some what like this

auto Testfun (string FFs, int Size) { return tuple(FFs, Size); }

void process(T ...)(T function(T args) coRoutine, T args) {
alias scRType = typeof(coRoutine(T.init));
PFresult.get = coRoutine(T);

void main() {
string Test ="C:\\Temp\\BACKUP1"; int Size = 1;
process(&Testfun, Test, Size);
}


Code : Working
import std.stdio: writeln;
import std.container.array;
import std.typecons: tuple;
import std.parallelism: taskPool;

auto Testfun (string FFs, int Size) { return tuple(FFs, Size); }

void process(T)(T function(string, int) coRoutine, string Test, 
int Size) {
alias scRType = typeof(coRoutine(string.init, int.init));
auto PFresult = taskPool.workerLocalStorage!scRType();
PFresult.get = coRoutine(Test, Size);
foreach(i; PFresult.toRange) { writeln(i[][]); }
}

void main() {
string Test ="C:\\Temp\\BACKUP1"; int Size = 1;
process(&Testfun, Test, Size);
}

From,
Vino.B


More information about the Digitalmars-d-learn mailing list