On Saturday, 6 January 2024 at 17:57:06 UTC, Paul Backus wrote:
On Friday, 5 January 2024 at 20:41:53 UTC, Noé Falzon wrote:
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!
It works for the same reason this example works:
```d
void printVar(alias var)()
{
import std.stdio;
writeln(__traits(identifier, var), " = ", var);
}
void main()
{
int x = 123;
int y = 456;
printVar!x; // x = 123
printVar!y; // y = 456
x = 789;
printVar!x; // x = 789
}
```
To clarify, what this actually compiles to is:
```d
void main()
{
int x = 123;
int y = 456;
void printVar_x()
{
import std.stdio;
writeln(__traits(identifier, x), " = ", x);
}
void printVar_y()
{
import std.stdio;
writeln(__traits(identifier, y), " = ", y);
}
printVar_x;
printVar_y;
x = 789;
printVar_x;
}
```
Which lowers to:
```d
struct mainStackframe
{
int x;
int y;
}
void printVar_main_x(mainStackframe* context)
{
import std.stdio;
writeln(__traits(identifier, context.x), " = ", context.x);
}
void printVar_main_y(mainStackframe* context)
{
import std.stdio;
writeln(__traits(identifier, context.y), " = ", context.y);
}
void main()
{
// this is the only "actual" variable in main()
mainStackframe frame;
frame.x = 123;
frame.y = 456;
printVar_main_x(&frame);
printVar_main_y(&frame);
frame.x = 789;
printVar_main_x(&frame);
}
Same with `map`.