Instantiation
Consider the following case:
template <typename A>
class Foo {
public:
int bar() { return 1; }
}
There is a difference between implicit and explicit instantiation of a class template.
Unless used, this class does not exist. It is instantiated upon use. There are 2 types of instantiation, and there are subtly but importantly distinct
Explicit Instantiation
template class Foo<int>;
The above line of code explicitly instantiates the class Foo<int>
. With explicit instantiation, all members of the class are instantiated.
Implicit Instantiation
Foo<int> foo;
The above line of code implicitly instantiates Foo<int>
. When implicitly instantiating, members are instantiated when used. This means, with only the above line of code Foo<int>::bar
is not instantiated.
Takeaway
When implicitly instantiating a template class, a member function which is not used anywhere in the code will not be instantiated. Practically, this means it won’t be type checked and can have compiler errors that will only surface when the function is used.