Trying to understand map being a template
H. S. Teoh
hsteoh at qfbox.info
Fri Jan 5 21:04:43 UTC 2024
On Fri, Jan 05, 2024 at 08:41:53PM +0000, Noé Falzon via Digitalmars-d-learn wrote:
> On the subject of `map` taking the function as template parameter, I
> was surprised to see it could still be used with functions determined
> at runtime, even closures, etc. I am trying to understand the
> mechanism behind it.
That's simple, if the argument is a runtime function, it is treated as a
function pointer (or delegate).
[...]
> In fact, how can the template be instantiated at all in the following
> example, where no functions can possibly be known at compile time:
>
> ```
> auto do_random_map(int delegate(int)[] funcs, int[] values)
> {
> auto func = funcs.choice;
> return values.map!func;
> }
> ```
[...]
The argument is taken to be a delegate to be bound at runtime. In the
instantiation a shim is inserted to pass along the delegate from the
caller's context.
T
--
Creativity is not an excuse for sloppiness.
More information about the Digitalmars-d-learn
mailing list