With regard to explicit instantiation (IIRC used when the template is declare in a header and defined in a cpp file because otherwise the linker would not be able to find it when using it somewhere else), if the template has a static member variable, will the explicit instantiation also instantiate and create the static member variable?
If you explicitly instantiate a class template, all non-template members will be instantiated, including static
data members as long as 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>;
The explicit instantiations at the bottom create definitions for static_data
and non_template_member()
for the types int
and double
. There won't be a definition for template_member(S)
as this is still an open set.
If you do not provide a [templated] definition for static_data
, it won't instantiate a corresponding definition.
The relevant section of the standard is 14.7.2 [temp.explicit] paragraph 8:
An explicit instantiation that names a class template specialization is also an explicit instantiation of the same kind (declaration or definition) of each of its members (not including members inherited from base classes and members that are templates) that has not been previously explicitly specialized in the translation unit containing the explicit instantiation, except as described below.
Without the member definition the static
member is only declared and the explicit instantiation would merely see the declaration being instantiated. With the definition the explicit instantiation becomes a definition.
An explicit instantiation of a class template also instantiates static data members. As per C++11, [temp.explicit]/8:
An explicit instantiation that names a class template specialization is also an explicit instantiation of the same kind (declaration or definition) of each of its members (not including members inherited from base classes) that has not been previously explicitly specialized in the translation unit containing the explicit instantiation, except as described below. [ Note: In addition, it will typically be an explicit instantiation of certain implementation-dependent data about the class. —end note ]
And none of the "described below" cases apply to static data members.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With