Let’s say I have the following code:
// templateClass.h
#ifndef TEMPLATE_CLASS_H
#define TEMPLATE_CLASS_H
template <typename T>
class tClass
{
public:
tClass();
};
#endif
// templateClassDef.inl
#ifndef TEMPLATE_CLASS_DEF_INL
#define TEMPLATE_CLASS_DEF_INL
template <typename T>
tClass<T>::tClass()
{
}
#endif
// normalClass.h
#include "templateClass.h"
class normal
{
public:
normal();
};
// normalClass.cpp
#include "normalClass.h"
#include "templateClassDef.inl"
normal::normal()
{
tClass<int> a;
}
// main.cpp
#include "templateClass.h"
#include "templateClassDef.inl"
#include "normalClass.h"
int main()
{
tClass<int> a;
normal b;
return 0;
}
Note that the inl file is NOT being included in the header as it normally is, but is instead included in the source files (I am aware that is not the standard way… this is just an example). Notice that normalcClass.cpp is instantiating tClass<int> and so is main.cpp.
I am curious as to whether the compiler has to construct the instantiation from the template class every time it encounters an explicit instantiation, considering it is the same type (i.e. tClass<int>) even though both instantiations occur in separate translation units (normalClass.cpp and main.cpp)? Also, will this increase in compile time (If the answer to the previous question is yes it will instantiate it again then this should also be yes)?
In general, yes, template classes are usually compiled every time they’re encountered by the compiler.