Answer the question
In order to leave comments, you need to log in
Template magic in D?
There are many functions with a signature:
I would like to make a template that would automatically adapt this interface to:
If there are constructors:AT Func(AT arg);<br>
Val AdaptedFunc(A a, Val v);<br>
AT(A, Val);<br>
Val(AT);<br>
Val AdaptedFunc(A a, Val v)<br>
{<br>
return Val(Func(AT(a, v)));<br>
}<br>
Val v = Adapter!Func(A a, Val v);<br>
Answer the question
In order to leave comments, you need to log in
Surely, after a year, the decision will not be relevant, but for language learners it can be useful.
module main;
import std.stdio;
import std.traits;
Val AdaptedFunc(alias Func, A, Val)(A a, Val V)
{
alias ReturnType!Func AT;
static assert(__traits(compiles, AT(a,V)), AT.stringof ~ " must have constructor this("~A.stringof~","~Val.stringof~")");
static assert(__traits(compiles, Val(AT(a,V))), Val.stringof ~ " must have constructor this("~AT.stringof~")");
return Val(Func(AT(a,V)));
}
struct Test1
{
string name;
int val;
this(string pName, Test2 test)
{
name = pName;
val = test.val;
}
}
Test1 test1Transform(Test1 test)
{
test.val *= test.val;
return test;
}
struct Test2
{
int val;
this(Test1 pVal)
{
val = pVal.val;
}
}
int main(string[] args)
{
Test2 testA;
testA.val = 2;
Test2 testB = AdaptedFunc!test1Transform("first", testA);
writeln(testB.val); // prints 4
getchar();
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question