Does instantiating a template instantiate its static data members?
关于显式实例化(当模板在头文件中声明并在cpp文件中定义时使用IIRC,否则链接器在其他位置使用时无法找到它),如果模板有静态成员变量,将显式实例化还实例化并创建静态成员变量?
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.
链接地址: http://www.djcxy.com/p/79876.html上一篇: 编译动态内容
下一篇: 实例化模板是否实例化其静态数据成员?