Function Template for Dynamic Parameter

vino.B bheeman.vino at hotmail.com
Sun Jul 1 11:19:50 UTC 2018


On Sunday, 1 July 2018 at 09:55:34 UTC, Timoses wrote:
> On Sunday, 1 July 2018 at 09:46:32 UTC, vino.B wrote:
>> All,
>>
>>    Request your help, the D document states that "Template 
>> functions are useful for avoiding code duplication - instead 
>> of writing several copies of a function, each with a different 
>> parameter type, a single function template can be sufficient" 
>> which mean we can passing any type of parameter using function 
>> template, similarly who we we pass in any number of parameter 
>> of any type(dynamic parameters) , like in python
>>
>> Python
>>
>> def myfunc(*arg)
>> def myfunc(**kwargs) // multiple key-value
>> def myfunc(*args, **kwargs): mix
>>
>> Do we have any thing similar to the above python in D
>> void (func(T)( T *args) // Example
>>
>>
>> Examples:
>> void func(T)(T x)
>> {
>>     writeln(x);
>> }
>> void main()
>> { func("x");  // pass a string }
>>
>>
>> void func(T)(T n3)
>> {
>>     writeln(n); // where n = 3 parameters (1, string, char)
>> }
>>
>> void func(T)(T n2)
>> {
>>     writeln(n); // where n = 3 parameters (1, string)
>> }
>>
>> void func(T)(T n1)
>> {
>>     writeln(n); // where n = 3 parameters (1 or string or char)
>> }
>>
>> From,
>> Vino.B
>
> Perhaps https://dlang.org/spec/template.html#variadic-templates
>
>     void func(T ...)(T args)
>     {
>         static assert(T.length <= 3);
>
>         static assert(is(T[0] == int)); // 1
>
>         pragma(msg, T.stringof);
>         foreach (arg; args)
>         {
>             writeln(arg);
>         }
>     }
>
>     void main()
>     {
>         func(3, "s", 1.3);
>         //func(1.3); // error, first argument is not an int, 
> see // 1
>     }

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

From,
Vino.B



More information about the Digitalmars-d-learn mailing list