The right way to use templates in g++

So far I have recommended a relatively simple approach for using templates in g++ programs. In this approach, you #include the .cc file defining all the methods of a templated class in every .cc file that uses the class, is simple but very wasteful. If you use the same template class with the same parameters (e.g., Stack<int>) in more than one source file, you include all of the code for Stack<int> in every file!

The solution is to include the .h file in most of the .cc files using the class, and to instantiate the template in only one compiled .cc file. The g++ info pages (accessible in emacs) describes how to do this:

Explicitly instantiate all the template instances you use, and compile with -fno-implicit-templates. This is probably your best bet; it may require more knowledge of exactly which templates you are using, but it's less mysterious than the previous approach, and it doesn't require any #pragmas or other g++-specific code. You can scatter the instantiations throughout your program, you can create one big file to do all the instantiations, or you can create tiny files like #include "Foo.h" #include "" template class Foo<int>; for each instance you need, and create a template instantiation library from those.
So if you put the above in, you should arrange for your Makefile to compile it into Foo-int.o, and link that into your code. Do not #include anywhere else in your code!
David Kotz; Last modified: Tue Feb 27 13:47:52 1996