How templates work (2) - Recursive templates

Simen Kjærås simen.kjaras at gmail.com
Mon Jun 1 13:00:36 UTC 2020


On Monday, 1 June 2020 at 10:20:14 UTC, Stefan Koch wrote:
> On Monday, 1 June 2020 at 09:05:51 UTC, Stefan Koch wrote:
>> Hi,
>>
>> it's time for the second part of my posts on templates.
>> Today we are going to look into how template recursion works, 
>> using the same substitution method that we learned about in 
>> the previous post.
>>
>> [...]
>
> Please do leave feedback.

Great work!

First off, a few minor typos:

> here the else branch is taken and it resolves to
> { alias Iota = AliasSeq!(); }.Iota => AliasSeq!();

That's the 'if' branch.

> I would like to note that although DMD just those steps;

s/just/does


Second, your Iota doesn't match D's existing iota - your takes a 
start and number of items, while the one in std.range takes 
beginning and end items. Here's the equivalent in templates:

template Iota(size_t from, size_t to) {
     static if (from >= to) {
         alias Iota = AliasSeq!();
     } else {
         alias Iota = AliasSeq!(from, Iota!(from+1, to));
     }
}

This may also be slightly easier to follow, since it's simply 
counting up in the 'from' parameter, rather than changing two 
values each step (so for Iota!(0, 2) you get AliasSeq!(0, 
Iota!(1, 2)) => AliasSeq!(0, AliasSeq!(1, Iota!(2, 2)) => 
AliasSeq!(0, AliasSeq!(1, AliasSeq!())))).


All in all though, a great walkthough on what happens behind the 
scenes. Makes me lightly disappointed I can't just write `alias x 
= { alias y = int; }.y;` in regular code.

--
   Simen


More information about the Digitalmars-d mailing list