Implicit instantiation (C++ only)
Unless a template specialization has been explicitly instantiated or explicitly specialized, the compiler will generate a specialization for the template only when it needs the definition. This is called implicit instantiation.
The compiler does not need to generate the specialization for nonclass, noninline entities when an explicit instantiation declaration is present.If the compiler must instantiate a class template specialization and the template is declared, you must also define the template.
For example, if you declare a pointer to a class, the
definition of that class is not needed and the class will not be implicitly
instantiated. The following example demonstrates when the compiler
instantiates a template class:
template<class T> class X {
public:
X* p;
void f();
void g();
1};
X<int>* q;
X<int> r;
X<float>* s;
r.f();
s->g();
The compiler requires the instantiation of the following
classes and functions: - X<int> when the object r is declared
- X<int>::f() at the member function call r.f()
- X<float> and X<float>::g() at the class member access function call s->g()
- class X when the pointer p is declared
- X<int> when the pointer q is declared
- X<float> when the pointer s is declared
template<class T> class B { };
template<class T> class D : public B<T> { };
void g(D<double>* p, D<int>* q)
{
B<double>* r = p;
delete q;
}
The assignment B<double>* r = p converts p of
type D<double>* to a type of B<double>*;
the compiler must instantiate D<double>. The
compiler must instantiate D<int> when it tries
to delete q.If the compiler implicitly instantiates a class template
that contains static members, those static members are not implicitly
instantiated. The compiler will instantiate a static member only when
the compiler needs the static member's definition. Every instantiated
class template specialization has its own copy of static members.
The following example demonstrates this:
template<class T> class X {
public:
static T v;
};
template<class T> T X<T>::v = 0;
X<char*> a;
X<float> b;
X<float> c;
Object a has a static
member variable v of type char*.
Object b has a static variable v of
type float. Objects b and c share
the single static data member v.An implicitly instantiated template is in the same namespace where you defined the template.
If a function template or a member function template specialization is involved with overload resolution, the compiler implicitly instantiates a declaration of the specialization.