- What does redundant template instantiations here mean?
Assume we have a template <typename T> class A {};
which is declared in the a.hpp
. We have two ways to instantiate an object in the a.cpp
:
1. explicit instantiation
- Explicit instantiation definition:
template class A <type>;
- Explicit instantiation declaration:
extern template class A <type>;
2. implicit instantiation
When code refers to a template in context that requires a completely defined type, or when the completeness of the type affects the code, and this particular type has not been explicitly instantiated, implicit instantiation occurs
When the TUs cannot find the explicit instantiation definition or declaration, tA<int> a;
will invoke implicit instantiation.
difference between specialization and instantiate
Let's return the Question: What does redundant template instantiations here mean?
I will divide it into several cases within one a.cpp
:
Case 1 ---- implicit instantiation
#include "a.h"
A<int> a;
=>
class A<int>
{
};
A<int> a;
Case 2 ---- implicit instantiation
#include "a..h"
A<int> a;
A<int> b;
=>
class A<int>
{
};
A<int> a;
A<int> b;
Case 3 ---- Explicit instantiation definition:
#include "a.h"
template class A<int>;
A<int> a;
=>
#include "a.h"
template class A<int>;
A<int> a;
Conclusion:
- Implicit instantiation will produce redundant template instantiations while explicit instantiation definition/declaration won't.
- Linker will remove such redundant template instantiations, but it will increase
link-time
.
If you wonder how does the linker work to remove redundant template instantiations, please read this thread: How does the linker handle identical template instantiations across translation units?