Metaprogramming, generate argument list.

Jack Applegame via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Aug 23 00:17:16 PDT 2016


On Monday, 22 August 2016 at 22:01:51 UTC, ciechowoj wrote:
> Is it possible to generate an argument list that contains 
> pointers to local variables at compile time?
>
> For example, consider following code:
>
> template Repeat(alias int N, alias variable)
> {
>     // Magic
>
>     alias Repeat = /* Even more magic */;
> }
>
> void foo(int* x, int* y, int* z)
> {
>     // [...]
> }
>
> void fun()
> {
>     int bar = 42;
>
>     foo(Repeat!(3, bar)); // want to replace it with &bar, 
> &bar, &bar
> }
This is impossible since pointers to local variables are unknown 
at compile time. But you can generate arguments list that 
contains functions that return pointers at run-time:

template Repeat(int N, alias variable) {
	auto ptr() @property { return &variable; }
	import std.meta : AliasSeq;
	static if(N == 1) alias Repeat = ptr;
	else alias Repeat = AliasSeq!(ptr, Repeat!(N-1, variable));
}

void foo(int* x, int* y, int* z) {
}

void main() {
     int bar = 42;
     foo(Repeat!(3, bar));
}


More information about the Digitalmars-d-learn mailing list