What does the alias attribute do here

Gary Willoughby dev at nomad.so
Tue Feb 4 11:54:19 PST 2014


On Tuesday, 4 February 2014 at 17:17:13 UTC, Adam D. Ruppe wrote:
> On Tuesday, 4 February 2014 at 17:09:02 UTC, Gary Willoughby 
> wrote:
>> What does the alias attribute do here:
>>
>>    void foo(alias bar)
>
> This specifically won't compile, alias params are only allowed 
> in a compile-time list. So
>
> void foo(alias bar)() { ... }
>
> would work.
>
>
> Anyway, what it does is you pass another symbol to the 
> function/template and the alias parameter works as the same 
> thing. So let's play with:
>
> void foo(alias bar)() {
>     import std.stdio;
>     writeln(bar);
> }
>
> void main() {
>     int a = 20;
>     foo!a(); // will print 20
> }
>
>
> What happened is foo!a passed the /symbol/, not just the 
> variable contents, the variable itself, as the alias parameter. 
> An important difference between this and a regular int 
> parameter is you can assign to it too:
>
>
> void foo(alias a)() {
>         import std.stdio;
>         writeln(a);
>         a = 50; // this is as if we literally wrote cool = 50; 
> in main()
> }
>
> void main() {
>         int cool = 20;
>         foo!cool();
>         assert(cool == 50); // passes
> }
>
>
> alias parameters differ from regular parameters because a 
> regular parameter can only be a type name. An alias parameter 
> can be another variable.
>
>
> You can also pass it functions and call them as if the user 
> wrote the call themselves - no pointers/delegates involved.

Ah great, thanks that makes perfect sense.


More information about the Digitalmars-d-learn mailing list