-
template instantiations
I have the following code:
Code:
void foo()
{
Class<int> c1, c2;
}
So two variables of Class<int>.
What happens at the technical level when the compiler sees this code? Does it generate two Class<int> {}; types and only during link time all the Class<int> types are reduced to one? Or does it only do that for variables in different translation units?
-
Within a single translation unit, there is no more than one class named Class<int>, but can be multiple instances of it.
Things are less clear cut with programs that have multiple translation units. Theoretically, the "export" keyword in the standard allows separation of class declarations from definitions (and therefore rationalisation of template instantiation). To date, only compilers based on the EDG front-end (most notably Comeau C++) support the "export" keyword. Compiler vendors consider full support of "export" to be prohibitive (the number of man-years to implement that support in the EDG front end was reportedly mind-boggling). Because of this, IIRC, exported templates are slated for complete removal from the next version of the C++ standard.
Because of that, with multiple translation units, things vary with compiler, compiler settings, and linker.
As a rough rule, the more sophisticated the compiler and linker, the more likely it is that the types (or, more accurately, their member functions) are rationalised across a program. With less sophisticated compilers and linkers (particularly those that don't work together for such things) the executable may contain an instantiation of each type that is local to, and therefore replicated for, each translation unit in which it is used.
Some compilers support some (compiler-specific) notion of "explicit template instantiation", which allows the programmer to manage things explicitly.
Which means, if you care about such things, you need to read your compiler documentation carefully. Quite a few compilers (and, if distributed with the compiler, the linkers) do support some features related to managing template instantation, but most don't enable them by default. Therefore it is necessary to find and understand the relevant settings.