Help needed to learn templates

Stanislav Blinov stanislav.blinov at gmail.com
Sat Mar 19 11:47:53 UTC 2022


On Saturday, 19 March 2022 at 05:54:26 UTC, Vinod K Chandran 
wrote:

> Question 1 - `U` is appearing in the first static if statement. 
> But we had to write `U` on the template line, right? Like - 
> `template rank(T, U)`

No.

> Question 2 - The statif if test is - `T t == U[ ]` What does 
> that mean ?

The test is not `T t == U[]`. It is `is(T t == U[], U)`.

https://dlang.org/spec/expression.html#is-identifier-equal

```
is ( Type Identifier == TypeSpecialization )

The condition is satisfied if Type is semantically correct and is 
the same as TypeSpecialization. The Identifier is declared to be 
either an alias of the TypeSpecialization or, if 
TypeSpecialization is dependent on Identifier, the deduced type.
```

You simply introduce new identifiers. Basically, the test means 
"is T an array of some type which I would like referred to as 
U?". Actually, the lower case `t` is not needed there, you can 
simply write `is(T == U[], U)`.

> Question 3 - if `T t == U[ ]` is the test, then I think when we 
> pass
> ```d
> rank!(int[ ][ ][ ])
> ```
> The test will be `int[ ][ ][ ] == U[ ]`, Right ?

Yes, and `U` then becomes `int[][]`. Which is why the template 
recurses down and instantiates itself with `U`, until `T` fails 
the test.


More information about the Digitalmars-d-learn mailing list