Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does instantiating a template instantiate its static data members?

Tags:

c++

templates

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?

like image 624
user129506 Avatar asked Jun 20 '14 11:06

user129506


2 Answers

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.

like image 106
Dietmar Kühl Avatar answered Nov 13 '22 03:11

Dietmar Kühl


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.

like image 41
Angew is no longer proud of SO Avatar answered Nov 13 '22 04:11

Angew is no longer proud of SO