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.
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(); }; X<int>* q; X<int> r; X<float>* s; r.f(); s->g();
The compiler requires the instantiation of the following classes and functions:
Therefore, the functions X<T>::f() and X<T>::g() must be defined in order for the above example to compile. (The compiler will use the default constructor of class X when it creates object r.) The compiler does not require the instantiation of the following definitions:
The compiler will implicitly instantiate a class template specialization if it is involved in pointer conversion or pointer to member conversion. The following example demonstrates this:
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.
Related References