M
M
Monnoroch2012-11-07 18:31:34
Programming
Monnoroch, 2012-11-07 18:31:34

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>

That is, if you write an adapter for each function manually, it will turn out like this:
Val AdaptedFunc(A a,  Val v)<br>
{<br>
  return Val(Func(AT(a, v)));<br>
}<br>

It is clear that this is not at all what you want. So far I have succeeded with the help of mixin templates, but this is also not what I want, but I want as a result of something like this code:
Val v = Adapter!Func(A a, Val v);<br>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NCrashed, 2013-01-05
@NCrashed

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 question

Ask a Question

731 491 924 answers to any question