template mixins vs alias

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 22 05:56:19 PST 2016


On Monday, 22 February 2016 at 13:35:10 UTC, Andrea Fontana wrote:
> Check this code:
> http://dpaste.dzfl.pl/fcf876acbbdc
>
> Structs A and B do the same things, in different way.
>
> Is there any difference/limitation between those?
>
> Andrea

The mixin variant generates a method. That means, you can 
reference members of the struct in the function.

Silly example:
----
mixin template Test(T)
{
     auto returnX() { return x; }
}
struct A
{
     int x;
     mixin Test!int;
}
----

With the alias variant you get an alias to a free function, not a 
method. So you couldn't reference x like above.

What's nicer about the alias version is that you see what symbol 
is being generated. It's obvious that `alias returnInit = 
returnInitImpl!int;` creates a symbol "returnInit". In the mixin 
variant, you have to read the template's source to see that.


More information about the Digitalmars-d-learn mailing list