1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
When i(static members) are defined in class templates, they
hi(class template: static members)
are defined for every new type for which the class template is
instantiated. As they are static
members, there will only be one member per type for which the class template
is instantiated. For example, in a class like:
verb( template <typename Type>
class TheClass
{
static int s_objectCounter;
};)
There will be em(one) tt(TheClass<Type>::objectCounter) for each different
tt(Type) specification. The following object definitions result in the
instantiation of just one single static variable, shared among the two
objects:
verb( TheClass<int> theClassOne;
TheClass<int> theClassTwo;)
Mentioning static members in interfaces does not mean these members are
actually defined. They are only em(declared) and must be em(defined)
separately. With static members of class templates this is no different. The
definitions of static members
hi(class template: static members)
are usually provided immediately following (i.e., below) the template
class interface. For example, the static member
tt(s_objectCounter)'s definition, positioned just below its class interface,
looks like this:
verb( template <typename Type> // definition, following
int TheClass<Type>::s_objectCounter = 0; // the interface)
Here tt(s_objectCounter) is an tt(int) and is thus independent of the
template type parameter tt(Type). Multiple instantiations of
tt(s_objectCounter) for identical tt(Type)s cause no problem, as the linker
will remove all but one instantiation from the final executable (cf. section
ref(TEMPFUNDECL)).
hi(pointer: to object)
In list-like constructions, where a pointer to objects of the class
itself is required, the template type parameter tt(Type) must be used when
defining the static variable. Example:
verbinclude(-a examples/statictype.cc)
As usual, the definition can be read from the variable name back to the
beginning of the definition: tt(s_objectPtr) of the class tt(TheClass<Type>)
is a pointer to an object of tt(TheClass<Type>).
When a static variable of a template's type parameter's type is defined,
it should of course not be given the initial value 0. The default constructor
(e.g., tt(Type())) is usually more appropriate. Example:
verb( template <typename Type> // s_type's definition
Type TheClass<Type>::s_type = Type();)
|