Topic: Explicit instantiations in same compilation unit
Author: jbn@lulea.trab.se (Johan Bengtsson)
Date: Sun, 25 Sep 1994 19:31:33 GMT Raw View
Just jumped into this newsgroup after a long absence to get the answer
of a specific question. Is the following source file correct,
or a multiple-template-instantiation error?
// afile.cc
template class vector<int>; // instantiate vector<int>
template class vector<int>; // ...once more!
[ end question, begin elaboration ]
If the answer is that the above is a valid C++ compilation unit,
then you need not read further, unless you are interested in a scheme
for guaranteeing that each explicit template instantiations occur
in exactly one compilation unit, even if multiple independent
libraries are involved.
"The Design and Evolution of C++" by Bjarne Stroustrup
in section 15.10.1 describes the syntax for explicit template
instantation. According to the book it is implementation-dependent
whether multiple explicit instantiations are rejected or not.
The reason is that "suppressing redundant explicit instantiations
could in general be very difficult".
However, suppressing redundant explicit instantiations
_within the same compilation unit_ seems trivial.
Below, I make a case that it is also essential that
this is done, for projects involving multiple libraries.
I used an early (the first?) compiler that supported templates
(ObjectStore C++ from Object Design Inc.). Because of some
trickiness with template instantiations I had to rely on explicit
instantiation. The compiler required that each instantiation was
specified in exactly one compilation unit (otherwise link errors).
I used the following scheme:
Assume we have two libraries (A and B) and an application program,
all of which use vector<int> and some other template instantiations.
Library A provides
// A_Instantiate.hh
template class vector<int>; // instantiate vector<int>
template class vector<SomeClassInA>;
...
Library B provides
// B_Instantiate.hh
template class vector<int>; // instantiate vector<int>
template class vector<SomeClassInB>;
...
The application program provides a special compilation unit to hold
all template instantiations used by library A and B and the program
itself:
// myapp_instantiate.cc
#include <A_Instantiate.hh>
#include <B_Instantiate.hh>
template class vector<int>;
template class vector<MyAppClass>
... other application-specific instantiations ...
In my case I had to do it this way (the syntax was different);
in future compilers this will be useful in order to significantly
reduce recompilation times.
So, will this scheme fly with all compilers conforming to
the upcoming C++ standard?
--
-------------------------------------------------------------------------
| Johan Bengtsson, Telia Research AB, Aurorum 6, S-977 75 Lulea, Sweden |
| Johan.Bengtsson@lulea.trab.se; Voice:(+46)92075471; Fax:(+46)92075490 |
-------------------------------------------------------------------------