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)?
Basically, templates are instantiated per compile unit, which increases compile time. There are some extensions and features in the new C++ standard to handle this issue, like explicit instantiation and externalization. See this doc for some explanations and optimization techniques:
http://gcc.gnu.org/onlinedocs/gcc/Template-Instantiation.html
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