Question about explicit template instantiation
Jarrett Billingsley
kb3ctd2 at yahoo.com
Sun Feb 10 18:33:58 PST 2008
"Edward Diener" <eddielee_no_spam_here at tropicsoft.com> wrote in message
news:fonlr1$2krb$1 at digitalmars.com...
> This is utterly confusing to me coming from C++. Instantiating templates
> in C++ produce a type. If a template instantiation is not a type, what is
> it ? Also how does one produce a type from a template in D ?
As Janice said, instantiating a template creates a namespace in which the
template parameters are replaced by the arguments given in the
instantiation.
C++'s templates are intrinsically bound to either classes or functions, and
instantiating a template in C++ gets you either a class or a function.
D's templates are more general; they simply declare a namespace in which one
or more declarations can exist, all parameterized by the template's
parameters.
It might help to know that this:
class A(T)
{
..
}
is _exactly_ equivalent (and in fact turned into this by the compiler) to:
template A(T)
{
class A
{
...
}
}
Why this works is because if a template contains exactly one declaration,
and that declaration has the same name as the template, referring to the
template instantiation refers to the symbol inside it. So:
A!(int).A a;
A!(int) b; // sugar for the previous line
Function templates work similarly.
void foo(T)()
{
...
}
==
template foo(T)
{
void foo()
{
}
}
So this function can be called either as foo!(int)() or as foo!(int).foo().
This extends to any kind of declaration.
template A(T, U)
{
T t;
U u;
}
template A(T)
{
// an alias is a declaration too.
alias A!(T, T) A;
}
alias A!(int, float) one; // one.t is int, one.u is float
// we don't have to say A!(char).A
alias A!(char) two; // both two.t and two.u are char
You can have more than one declaration in a template, but then the
"automatic symbol use" magic stops happening.
More information about the Digitalmars-d
mailing list