Is it possible for the compiler to duplicate instantiations of a same template across several translation units?
For instance, if you have a.cpp which use a st
As sharptooth says, the final binary will only contain one instantiation. But the templates will still be instantiated everytime they are encountered in a compilation unit. If you want some compilation speed, in C++0x we get the extern template
s. It works like normal extern
variables, in that it has to be specified in at least one compilation unit, but the compiler wont instantiate the template in this unit. See here and this draft (14.7.2 [temp.explicit]) for more infos.
I think that the compiler uses the same mechanism as with member functions of ordinary classes. It can make them inline
and I presume that it leaves information around that the linker uses to sort it out for the final binary.
The only difference is that the compiler 'writes' the definitions - that is the 'instantiation' of a template - but it manages to make exactly the same instantiation whilst compiling either of a.cpp or b.cpp
This can happen while the project is being compiled, so different .obj files will have copies of the same instantiation. When the binary is linked the linker will eliminate all redundant copies of an instantiation, so the end binary will have only one copy.
It is possible, but only if you explicitly instantiate them, but then you will get a linker errors :
// header.hpp
template< typename T >
class A
{
};
// source1.cpp
template class A< int >;
// source2.cpp
template class A< int >;
If you are not explicitly instantiating templates, then any decent linker will easily eliminate copies.