Question about explicit template instantiation

Tyro[a.c.edwards] no at spam.com
Sat Feb 9 16:44:53 PST 2008


Edward Diener さんは書きました:
> I am working my way throught the pdf documentation ( 1.0 ) regarding 
> templates in D and in the topic about explicit template instantiation 
> and I came across the lines below, which have me stumped:
> 
> ----------------------------------------------------------------
> 
> A template instantiation can be aliased:
> template TFoo(T) { alias T* t; }
> alias TFoo!(int) abc;
> abc.t x; // declare x to be of type int*
> Multiple instantiations of a TemplateDeclaration with the same 
> TemplateArgumentList, before
> implicit conversions, all will refer to the same instantiation. For 
> example:
> template TFoo(T) { T f; }
> alias TFoo!(int) a;
> alias TFoo!(int) b;
> ...
> 
> a.f = 3;
> assert(b.f == 3); // a and b refer to the same instance of TFoo
> This is true even if the TemplateInstances are done in different modules.
> 
> ----------------------------------------------------------------
> 
> My confusion with the above is that an alias, when referring to a type, 
> is the equivalent of a C++ typedef AFAICS. So 'a' and 'b' above are 
> types ( because the instantiated template is a type ) and then I see the 
> 'a.f=3' line followed by the 'assert(b.f == 3)' line and I can not 
> understand how a type can be used in either expression.
> 
> I am also assuming that the line beginning with "Multiple instantiations 
> of a..." only mean that the 'a' and 'b' refer to the same type, but 
> perhaps I have missed something in this explanation.

The problem here is that you are misconstruing templates to be classes. 
Templates, like classes and other types, can be aliased, however since a 
template is not a type you couldn't use TFoo!(int) to declare a 
variable. This also applies to the derived aliases 'a' and 'b'.

The templated class however, is a different story. Take the following 
code snipet for example:

	class Bar(T)
	{
		T f;
	}

	alias bar!(int) y;
	alias bar!(int) z;

Here Bar(T) is a class, therefore Bar!(int) is a class instanciation: a 
type. Hence, the aliases, 'y' and 'z' are also types. Any attempts to 
use them as with the previous example, will result in an error.

	y.f = 3; // Error y is an instanciated class
	assert(z.f == 3); // Error y is an instanciated class

Proper usage in this case is the same as any other class:

	y Y;  // OK
	Y.f = 3; // Error memory not yet allocated for Y
	Y = new y; // OK
	Y.f = 3;  // OK
	assert(Y.f == 3); //OK

Hope that helps somewhat!



More information about the Digitalmars-d mailing list