www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - alias template parameter

reply "Sergei Nosov" <sergei.nosov gmail.com> writes:
Hi!

I've been thinking about how alias template parameters work and 
I'm really confused =)

It makes perfect sense for literals, names, etc. But what I can't 
get is how does it work for delegates.

If I have a function
auto apply(alias fun, T...)(T args)
{
     return fun(args);
}

And then I have
int y = 2;
apply!(x => y)(1);

How in the world does this work? Is the context address known at 
compile-time?
Jun 21 2013
next sibling parent QAston <qaston gmail.com> writes:
On Friday, 21 June 2013 at 14:08:43 UTC, Sergei Nosov wrote:
 Hi!

 I've been thinking about how alias template parameters work and 
 I'm really confused =)

 It makes perfect sense for literals, names, etc. But what I 
 can't get is how does it work for delegates.

 If I have a function
 auto apply(alias fun, T...)(T args)
 {
     return fun(args);
 }

 And then I have
 int y = 2;
 apply!(x => y)(1);

 How in the world does this work? Is the context address known 
 at compile-time?
y is allocated on the heap and the pointer is implicitly passed to the apply, or is a field of a struct if you use map!(x => y) instead.
Jan 23 2016
prev sibling parent Marc =?UTF-8?B?U2Now7x0eg==?= <schuetzm gmx.net> writes:
On Friday, 21 June 2013 at 14:08:43 UTC, Sergei Nosov wrote:
 If I have a function
 auto apply(alias fun, T...)(T args)
 {
     return fun(args);
 }

 And then I have
 int y = 2;
 apply!(x => y)(1);

 How in the world does this work? Is the context address known 
 at compile-time?
No, but because lambdas are always unique, there will always be a dedicated template instance for every time you do this. The compiler will then hard-wire that instance to make it able to access the context pointer. By the way, you can also pass local variables by alias, in which case the same will happen. I guess it does so by passing the offset of the variable in the current stack frame (unless it's inlined and optimized, of course), but I don't know the details. I guess it's up to the compiler.
Jan 24 2016