Copy parameters from function passed as an alias

bauss jj_1337 at live.dk
Tue Oct 9 14:43:45 UTC 2018


Is there a way to copy parameters from a passed function as an 
alias.

Ex:

void foo(alias fun)(...);

where ... should be the parameters of fun.

Of course std.traits.Parameters works like:

void foo(alias fun)(Parameters!fun);

But the catch is that you don't get the identifiers.

So what is the next alternative?

Okay let's just make it a template then ..

template foo(alias fun)
{
   static const parameterTypes = 
Parameters!(fun).stringof[1..$-1].split(", ");
   static const parameterNames = [ParameterIdentifierTuple!(fun)];

   private string generateParameters()
   {
     string[] s = [];

     static foreach (i; 0 .. parameterTypes.length)
     {
       s ~= parameterType[i] ~ " " ~ parameterNames[i];
     }

     return s.join(",");
   }

   void foo(mixin(generateParameters()))
   {
     ...
   }
}

Hmmm well this doesn't work because mixin cannot be placed there.

So the next alternative is a long ugly mixin like:

template foo(alias fun)
{
   static const parameterTypes = 
Parameters!(fun).stringof[1..$-1].split(", ");
   static const parameterNames = [ParameterIdentifierTuple!(fun)];

   private string generateParameters()
   {
     string[] s = [];

     static foreach (i; 0 .. parameterTypes.length)
     {
       s ~= parameterTypes[i] ~ " " ~ parameterNames[i];
     }

     return s.join(",");
   }

   mixin("void foo(" ~ generateParameters() ~ ") {" ~ q{
     ...
   } ~ "}");
}

There must be a better way to do this.

Ex.

class Foo
{
   void a(int b, int c) { }
}

When passed to foo like "foo!(Foo.a)" should produce:

void foo(int b, int c)
{
   ...
}


More information about the Digitalmars-d-learn mailing list