Help needed to learn templates
Ali Çehreli
acehreli at yahoo.com
Sat Mar 19 15:58:25 UTC 2022
On 3/19/22 06:38, Vinod K Chandran wrote:
> On Saturday, 19 March 2022 at 11:47:53 UTC, Stanislav Blinov wrote:
>>
>> No.
>>
> First of all Thanks for the reply. The answer "No" is a wonder to me.
I wrote a chapter about the is expression but it's still mysterious to
me. :)
ddili.org/ders/d.en/is_expr.html
I may be saying some things wrong there but that's my mental model.
> Because, from my point of view, `U` is coming from nowhere.
Agreed. It is similar to U's coming from nowhere below:
void foo(U)(U[] array) {
}
So, in my mental model, that use of the is expression is the same but
written in the reverse order from foo above:
static if (is(T t == U[], U))
It means "if T matches U[] and U is a type". "a type" because it is just
U in the is expression list.
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:
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;
}
}
Or one can separate the logic in two template definitions:
import std.traits : isArray;
template rank(T)
if (isArray!T)
{
import std.range : ElementType;
enum size_t rank = 1 + rank!(ElementType!T);
}
template rank(T)
if (!isArray!T)
{
enum size_t rank = 0;
}
However, note how the template constraints had to be repeated as
isArray!T and !isArray!T in that case.
> My
> understanding is, we can use any parameter of a template inside the
> template. So in this case `U` is not in the parameter list. It is
> suddenly appearing in that `static if`.
In my mental model, the is expression uses at least a part of the
template system.
>> you can simply write
>> `is(T == U[], U)`.
>>
> So the `T` is not the type.
T is the type because it is introduced as simply T in the parameter
list. If it were 'int T', then it would be an int. So in that sense, it
is a type-kind template parameter.
> It's the parameter. Right ? So a template
> doesn't need a type. Only the parameter, right ?
The way I read it is: "T is a type that matches U[] where U is a type as
well."
> (I think I am too dumb
> to ask this. Please forgive me.)
Not at all! The is expression is the weirdest part of D.
Ali
More information about the Digitalmars-d-learn
mailing list