Help needed to learn templates

Vinod K Chandran kcvinu82 at gmail.com
Sat Mar 19 17:42:57 UTC 2022


On Saturday, 19 March 2022 at 15:58:25 UTC, Ali Çehreli wrote:
>
> I wrote a chapter about the is expression but it's still 
> mysterious to me. :)
>
>   ddili.org/ders/d.en/is_expr.html
>

Thanks for the reply. I think I choose the wrong book. I knew 
about your book but I thought this one is specially written for 
templates. I will read the template chapters in **`Programming in 
D`**.

> It means "if T matches U[] and U is a type". "a type" because 
> it is just U in the is expression list.
>
So as per the eponymous trick, **`enum size_t rank`** will be 
executed directly. Right ? But in that case, **`rank`** template 
doesn't take a parameter. There is only the type parameter which 
is **`T`**. So I am still in confusion about **`U`**.

> I believe at least some of the traits have been added since 
> that doc document was written. I would write it in a much 
> simpler way using template constraints today:
>
> ```d
> template rank(T) {
>   import std.traits : isArray;
>   import std.range : ElementType;
>
>   static if (isArray!T) {
>     enum size_t rank = 1 + rank!(ElementType!T);
>
>   } else {
>     enum size_t rank = 0;
>   }
> }
> ```
>
This template is very easy to understand and I have no confusions 
about it. Because, it only takes **`T`** as type parameter and 
there is no magical **`U`**.

> However, note how the template constraints had to be repeated 
> as isArray!T and !isArray!T in that case.
>
Yeah, I noted.

> Not at all! The is expression is the weirdest part of D.
>
Oh I see.




More information about the Digitalmars-d-learn mailing list