Does a template instance create its static data items?

As for the explicit instance (IIRC is used when the template is declared in the header and defined in the cpp file, because otherwise the linker cannot find it when used elsewhere), if the template has a static member variable, will the explicit instantiation also create an instance and create static member variable?

+7
c ++ templates
source share
2 answers

If you explicitly create an instance of a class template, all non-template members will be created, including static members if they also have a definition. For example:

 template <typename T> struct foo { static int static_data; void non_template_member() {} template <typename S> void template_member(S) {} }; template <typename T> int foo<T>::static_data = 0; template struct foo<int>; template struct foo<double>; 

Explicit instantiations below create definitions for static_data and non_template_member() for types int and double . There will be no definition for template_member(S) , as this is still an open collection.

If you have not provided a definition [templated] for static_data , it will not create the corresponding definition.

The relevant section of the standard is 14.7.2 [temp.explicit], clause 8:

An explicit instantiation, which calls the specialization of a class template, is also an explicit instance of the same type (declaration or definition) of each of its members (not including members inherited from base classes and members that are templates) that were not previously explicitly specialized in the block a translation containing an explicit instantiation, except as described below.

Without a member definition, a static member is only declared, and an explicit instantiation will simply see that the created declaration is created. With a definition, explicit instantiation becomes a definition.

+3
source share

Explicitly creating a class template also instantiates static data. According to C ++ 11, [temp.explicit] / 8:

An explicit instantiation, which refers to the specialization of a class template, is also explicitly the same type (declaration or definition) of each of its members (not counting the members inherited from the base classes) that were not previously explicitly specialized in a translation unit containing an explicit instance, for except as described below. [Note. Also, usually it will be explicit some implementation-specific class data. -end note]

And none of the cases described below apply to static data members.

+1
source share

All Articles