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

evilrat evilrat666 at gmail.com
Mon Mar 29 18:33:39 UTC 2021


On Monday, 29 March 2021 at 17:52:13 UTC, Gavin Ray wrote:
> Trying to read this function signature:
>
>     void my_func(T, XS)(string a, string b, string c, lazy T 
> function(XS)[] t...)
>
> Does this say "Generic void function 'my_func', which takes two 
> generic/type params "T" and "XS", and is a function of type 
> "string a, string b, string c", and..." (this is where it 
> starts to get hazy for me):
>
> How does one interpret/read this:
>
>    lazy T function(XS)[] t...

A tuple of functions that takes XS argument(s) and returns T.

'...' part is a tuple/variadic arguments, however with function 
it is somewhat wacky and requires an array notation [], otherwise 
compiler treats it like a mere pointer for some reason, same with 
t[0]() call.

Also even though it says just XS in function parameters it has 
this special meaning, basically 'argument list'. (you can do cool 
tricks like this 
https://dlang.org/phobos/std_traits.html#Parameters)

lazy is parameter storage on function argument.

> Also I noticed that no explicit generic types were provided in 
> your call. I assume this means that D's type system is similar 
> to Typescript's then, where it's a logical constraints and will 
> try to "fit the holes" so to speak.
>
> In Typescript it works like this:
>
>   function myFunc<T>(arg: T) {}
>   myFunc(1) // T is inferred to be type "number"
>   myFunc("a") // T is inferred to be type "string"
>   myFunc<number>(1) // Same as above, but explicit, maybe 
> useful if you want to verify arg, else pointless
>
> It seems like potentially D is similar here?

I'm not that familiar with TypeScript but it looks close enough 
to what C# and C++ does, but yes it is like you described it, 
except explicit types is not to verify but to force it to be of 
that type when compiler is too confused or you need to use some 
specific base class or interface.


More information about the Digitalmars-d-learn mailing list