Question about explicit template instantiation

Edward Diener eddielee_no_spam_here at tropicsoft.com
Sun Feb 10 12:05:40 PST 2008


Janice Caron wrote:
> On 10/02/2008, Edward Diener <eddielee_no_spam_here at tropicsoft.com> wrote:
>> But I think I understand them now, but hopefully someone will clarify
>> things for me. It seems in D one can instantiate a temporary object from
>> a type which has a default constructor simply by using the type, whereas
>> in C++ one must use the type followed by '()'. So whereas if X were a
>> class with a default constructor with the data member Y, in C++ one
>> would use 'X().Y' to access the temporary's Y data member while in D it
>> appears one can use 'X.Y' to access the temporary's data member.
> 
> Alas no. You can omit the brackets, but you cannot omit the word
> "new". Thus, it would be either
> 
>     new X().Y
> 
> or
> 
>     (new X).Y

Understood. I forgot all non-struct classes must be in GC memory.

> 
> A template is not necessarily a class. You can have template classes,
> but not all templates are classes. You can also have template
> functions, but not all templates are functions. The most general
> statement would probably be that a template is a namespace. Thus:
> 
>     template MyNamespace(T)
>     {
>         int x;
>     }

A template being a namespace in D is certainly different from C++.
> 
> generates a different namespace for each different type of T. So in
> the above example, x is a global variable, not a member variable,
> within MyNamespace!(T) for some T. Therefore:
> 
>     MyNamesspace!(int).x
> 
> is a different variable from
> 
>     MyNamespace!(double).x
> 
> because the Ts are different. If I choose to save typing by writing:
> 
>     alias MyNamespace!(int) A;
>     alias MyNamespace!(double) B;
> 
> then A.x and B.x would still be different global variables. However,
> if I later write
> 
>     alias MyNamespace!(int) C;
> 
> then C refers to the /same/ namespace as A, and hence A.x and C.x are
> the exact same global variable.

This is confusing to me coming from C++. In C++ instantiating a class 
template produces a type. Is that not the way D works ? If not, what 
does instantiating a template produce in D and, if it does not produce a 
type, how does one instantiate a template which does produce a type in D ?



More information about the Digitalmars-d mailing list