How to declare "type of function, passed as an argument, which should have it's type inferred"? (or if D had an "any" type)

Ali Çehreli acehreli at yahoo.com
Mon Mar 29 16:20:59 UTC 2021


On 3/29/21 8:13 AM, Gavin Ray wrote:

 > Brief question, is it possible to write this so that the "alias fn" here
 > appears as the final argument?
 >
 >    auto my_func(alias fn)(string name, string description, auto 
otherthing)

Yes, as a type template parameter but you would have to constrain the 
parameter yourself (if you care):

import std.stdio;
import std.traits;
import std.meta;

auto myFunc(F)(string name, F func)
{
   // This condition could be a template constraint but they don't
   // support error messages.
   static assert (is (Parameters!func == AliasSeq!(string)),
                  "'func' must be a callable that takes 'string'.");
   return func(name);
}

void main() {
   // One trouble with this "solution" is that for the compiler to
   // know the return type of the lambda, the parameter must be
   // declared as 'string' (in this case).
   writeln(myFunc("foo", (string a) => a ~ '.'));
}

Ali



More information about the Digitalmars-d-learn mailing list