Function Template for Dynamic Parameter

Timoses timosesu at gmail.com
Sun Jul 1 12:07:55 UTC 2018


On Sunday, 1 July 2018 at 11:19:50 UTC, vino.B wrote:
> On Sunday, 1 July 2018 at 09:55:34 UTC, Timoses wrote:>
> Hi Timoses,
>
>   Thank you very much, can you help me on how to rewrite the 
> below using Variadic template
>
> Passing function as a parameter to another function:
>
> void ptFun(T)(T function(string, string, int) coRoutine, 
> Array!string Dirlst, ) {
> alias scRType = typeof(coRoutine(string.init, string.init, 
> int.init));
>
> where the "function(string, string, int) coRoutine" should be a 
> variadic function

What's your use case?

You can pretty much pass anything to a template and use "static 
if" and "static foreach" in the template to steer how the 
template is instantiated.

     void func(T ...)(T args)
     {
         foreach (i, arg; args)
         {
             static if (isSomeFunction!(T[i]))
             {
                 arg();
             }
             else
                 writeln(arg);
         }
     }

     unittest
     {
         func(() => writeln("I'm a lambda function), "I'm a 
string", 3);
     }

which would print:

I'm a lambda function
I'm a string
3


I'm actually a bit suprised that `isSomeFunction!(T[i])` works 
here, I'd expect an error because `i` looks like a run-time 
variable... And using that in a compile-time (static if) 
statement usually throws a CT error.


With templates one has to think "compile-time". Any "static if", 
"static foreach" or alias declarations are compile time 
constructs. What results from that after compilation is an 
instantiated template for a specific use case. For example in 
above case the template exists (is instantiated) with the 
template parameters `(void function() @safe, string, int)`.

A good source to get some more insights is always:
http://ddili.org/ders/d.en/templates.html
(including all other sections of the book)


More information about the Digitalmars-d-learn mailing list