|
| guestgulkan (1299) | |||||||||||
| Template Instantiation I was looking around for something to wite a small article about and this seems to a good one. The forum gets a fair number of post concerning this problem where the OP has split the template into a *.h file and a *.cpp file and gets linker problems. The usual answer given to this is to put all the template stuff into the *.h file because it has to be done this way. the class/functions. That is not entirely true. C++ has Implicit template instantiation and Explicit instantiation IMPLICIT INSTANTIATION In template.h
In main.cpp
In the example above, the complete template definition is in the header file which is included by main.cpp - so there are no problems during compiling and linking. If we were to forget to do a definition of the displayData() function then we would have got a LINKER error NOT a COMPILER error. //=========================================================================================// EXPLICIT INSTANTIATION Let's say we want to split our template class between a header file and a source file. So we have main.cpp and template.cpp. We compile both files but get Linker errors because NO actual code from the template.cpp file would have been instantiated. To get the compiler to instantiate the required code we can use explict instantiation. template.h
template.cpp
main.cpp
The important part is the last couple of lines in template.cpp We know that we will be needing a myTemplate<int> and a myTemplate<float> so we explicitly ask the compiler to generate code for all the instantiable parts for these two class types. Notice the way the instantiation directive is written. We can now compile and link our code successfully. We can also explicitly instantiate template functions, or individual template class member functions. | |||||||||||
| Bazzy (4118) | |
Actually, C++ allows templates to be defined in a separated sourcefile by using the export keywordUnfortunately C++ compilers usually don't support this feature: http://en.wikipedia.org/wiki/Export_%28C%2B%2B%29#Compatibility | |
| guestgulkan (1299) | |
| True - the standard does allow this - but it is so rarely implemented by compilers. MSVC does not support it, neither does GCC, and only partial support on Intel Compilers. | |
| RomaHagen (1) | |
| Thanks for the short and exact answer for this annoying question! But what if I want to instantiate my template not with builtin types. For example with some other classes from some library. I don't want to make my template header dependent on the header from that other library. Then the only option is to have one *.h source file. Am I right? Regards. | |
| Bazzy (4118) | |
| Yes (unless you have a cool export-compliant compiler) | |
This topic is archived - New replies not allowed.
