Question about explicit template instantiation
Edward Diener
eddielee_no_spam_here at tropicsoft.com
Sun Feb 10 14:31:36 PST 2008
Janice Caron wrote:
> On 10/02/2008, Edward Diener <eddielee_no_spam_here at tropicsoft.com> wrote:
>>> template MyNamespace(T)
>>> {
>>> int x;
>>> }
>
>> This is confusing to me coming from C++. In C++ instantiating a class
>> template produces a type. Is that not the way D works ?
>
> That's /exactly/ the way that D works. With CLASS templates, D works
> just like C++. No problem. Compare: c++
>
> template<class T> class A
> {
> int x;
> };
>
> A<int> a1;
> A<double> a2;
>
> and the D equivalent:
>
> class A(T)
> {
> int x;
> }
>
> auto a1 = new A!(int);
> auto a2 = new A!(double);
>
> They're exactly the same, except that D has nicer syntax. I don't
> think /class/ templates are confusing you at all! I think what's
> confusing you is that in D you can have /namespace/ templates, which
> don't exist in C++.
The explanation for Class Templates in the D1 doc does not explain
anything at all. That is why I assumed the template A(T) notation
referred to the equivalent of the C++ class template.
>
> Let me make an approximate C++ translation. Here's the D again:
>
> template A(T)
> {
> int x;
> }
>
> That is roughly equivalent to, in C++
>
> namespace A_int
> {
> int x;
> }
>
> namespace A_float
> {
> int x;
> }
>
> namespace A_double
> {
> int x;
> }
>
> ...and so on for every imaginable type. Now it should be clear to you
> that A_int::x is a different variable from A_float::x, yes?
Now I understand. I was surely fooled by the doc.
>
> For a namespaces to be "instantiated" just means that the
> corresponding chunk of code is there. To be /not/ instantiated would
> mean that it isn't there - which is just as well really, because there
> are in infinite number of possible types!
>
> To instantiate a namespace template, you only have to refer to it. I
> doesn't matter how.
>
> Clear?
I think so. Instantiating a namespace template merely puts the
equivalent code, with the types you instantiate it with substituted each
time those types are referred to in the namespace, directly into your
source.
I still do not understand what the object used for the instantiation is.
In your example above what is:
A!(int)
? Is it some kind of namespace ? Can I say:
A!(int) x;
? If so, what is x ?
More information about the Digitalmars-d
mailing list