Trying to understand map being a template

Noé Falzon falzon.noe at gmail.com
Fri Jan 5 20:41:53 UTC 2024


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.

The commented out line causes the error that `choice(funcs)` 
cannot be determined at compile time, which is fair, but how is 
it not the same case for `func` two lines above? I thought it 
might be because the functions are literals visible at compile 
time, but the closure makes that dubious.

```
import std.stdio;
import std.algorithm;
import std.random;

void main()
{
	int r = uniform(0,100);

	int delegate(int)[] funcs = [
		x => x * 2,
		x => x * x,
		x => 3,
		x => x * r		// Closure
	];

	auto foo = [1,2,3,4,5];

	foreach(i; 0..10)
	{
		// This is fine:
		auto func = funcs.choice;
		writeln(foo.map!func);

		// This is not?
		// writeln(foo.map!(funcs.choice));
	}
}
```

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;
}
```

Thank you for the insights!






More information about the Digitalmars-d-learn mailing list