You must use the extern template to prevent the compiler from creating an instance of the template when you know that it will be created somewhere else. It is used to reduce compilation time and object file size.
For example:
// header.h template<typename T> void ReallyBigFunction() { // Body } // source1.cpp #include "header.h" void something1() { ReallyBigFunction<int>(); } // source2.cpp #include "header.h" void something2() { ReallyBigFunction<int>(); }
This will result in the following object files:
source1.o void something1() void ReallyBigFunction<int>()
If both files are connected to each other, one void ReallyBigFunction<int>() will be discarded, which will lead to lost compilation time and the size of the object.
In order not to waste compilation time and the size of the object file, the extern keyword exists, which forces the compiler not to compile the template function. You should use this if and only if you know that it is used in the same binary somewhere else.
Change source2.cpp to:
// source2.cpp #include "header.h" extern template void ReallyBigFunction<int>(); void something2() { ReallyBigFunction<int>(); }
As a result, the following object files appear:
source1.o void something1() void ReallyBigFunction<int>()
When both of them are connected to each other, the second object file will simply use the symbol from the first object file. There is no need to discard and not waste time collecting and the size of the object file.
This should be used only in the project, for example, if you use a template of type vector<int> several times, you should use extern in all but one source file.
This also applies to classes and functions as one and even functions of template members.
Dani Nov 15 2018-11-11T00: 00Z
source share