Why defining alias and not auto when using a template?

Frustrated Who at where.com
Fri Apr 4 09:03:48 PDT 2014


On Friday, 4 April 2014 at 13:23:48 UTC, Bienlein wrote:
> Hello,
>
> I took some code snippet from some sample D code and modified 
> it a bit:
>
> template TCopy(T, V) {
>   private int i = 2;
> 	
>   void copy(out T to, out V to2, T from) {
>     to = from;
>     to2 = from;
>     writeln("i: ", i);
>   }
> }
>
> void main(string[] args)
> {
> 	int x = 2;
> 	int y = 2;
> 	alias myCopy = TCopy!(int, int);	
> 	myCopy.copy(x, y, 37);
> 	writeln("x: ", x, " y: ", y);
> }
>
> My question is now why I have to declare and alias as in
>
> alias myCopy = TCopy!(int, int);
>
> If I define auto instead of alias, it does not compile. My 
> question is why defining auto does not work. I would consider 
> this more intuitive.
>
> Thanks, Bienlein


When you type TCopy!(int, int) you are not creating an expression 
with a return variable. TCopy!(int, int) has no return variable 
so auto can't work(What would be the return value?).

All TCopy is, is a compile time container that contains a 
variable i and a method copy. It contains no return value, hence 
auto can't work.

Now, TCopy!(int, int).i or TCopy!(int, int).copy are "things" 
that are in the template that can be used.

About the only thing you could do is use an eponymous template 
like



> template TCopy(T, V) {
>   private int i = 2;
> 	
>   void copy(out T to, out V to2, T from) {
>     to = from;
>     to2 = from;
>     writeln("i: ", i);
>   }

     T TCopy() { return null; }
> }

then

auto x = TCopy!(int, int)(someTvalue);

then x would be of type T, the return value of the TCopy 
function(not the template because it doesn't have a return value).



More information about the Digitalmars-d-learn mailing list