The Wikipedia article says this:
instantiating a class template does not cause its member definitions to be instantiated.
I can't imagine any class in C++ being instantiated, whether from a template or not, where that classes members were not also instantiated?
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation.
In order for any code to appear, a template must be instantiated: the template arguments must be provided so that the compiler can generate an actual class (or function, from a function template).
Template instantiation involves generating a concrete class or function (instance) for a particular combination of template arguments. For example, the compiler generates a class for Array<int> and a different class for Array<double>.
The bodies of template classes and inline (or static) template functions are always instantiated implicitly when their definitions are needed. Member functions of template classes are not instantiated until they are used. Other template items can be instantiated by using explicit instantiation.
Many early C++ compilers instantiated all member functions, whether you ever called them or not.
Consider, for example, std::list
, which has a sort
member function. With a current, properly functioning compiler, you can instantiate list
over a type that doesn't support comparison. If you try to use list::sort
, it will fail, because you don't support comparison. As long as you don't call sort
for that list, it's all fine though, because list<T>::sort
won't be instantiated unless you call it.
With those older, poorly functioning compilers, however, trying to create list<T>
meant that list<T>::sort
was instantiated even though you never used it. The existence of list::sort
meant that you needed to implement <
for T
, just to create a list<T>
, even if you never actually used sort
on a list of that type at all.
The standard clearly says that (both non-template and template) member methods instantiation should happen only when used.
An excerpt from C++ standard (N3690 - 14.7.1(2) Implicit instantiation)
2 Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side-effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.
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