How to declare "type of function, passed as an argument, which should have it's type inferred"? (or if D had an "any" type)
Gavin Ray
user at example.com
Mon Mar 29 17:52:13 UTC 2021
On Monday, 29 March 2021 at 17:02:40 UTC, evilrat wrote:
>
> Also with delegates (lazy), you get the type checks however you
> must have to declare parameters on call site, which can be PITA
> in the future when doing refactoring will be necessary.
>
> Better plan ahead as the number of changes will explode when
> you make quite a number of these and decide to change
> params/returns.
>
> ```
> import std.stdio;
>
> void my_func(T, XS)(string a, string b, string c, lazy T
> function(XS)[] t...)
> {
> // call function, just the first one, can call all of them
> as well
> t[0](a);
>
> // can get the result too, mind the future refactoring
> needs tho
> // T res = t[0]();
> }
>
> void main()
> {
> my_func("name", "description", "otherthing", (string x) {
> writeln(x);
> return x;
> });
>
> // no function, compile error
> // my_func("name", "description", "otherthing");
> }
> ```
-----------------------------------------------------------------------
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...
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?
More information about the Digitalmars-d-learn
mailing list