Automatic instantiation

To instantiate templates automatically, include the template definition file in all source files that use the template, then use the template members like any other type or function. The compiler automatically generates code for a template instantiation whenever it sees a new one. Listing 1 shows how to automatically instantiate the templates for class Templ and class Max.

Listing 1. myprog.cp: A Source File that Uses Templates

#include <iostreams.h>
#include "templ.cp" // includes templ.h as well

void main(void) {
Templ<long> a = 1, b = 2;
// The compiler instantiates Templ<long> here.
cout << Max(a.Get(), b.Get());
// The compiler instantiates Max<long>() here.
};

If you use automatic instantiation, the compiler might take longer to translate your program because the compiler has to determine on its own which instantiations you need. It also scatters the object code for the template instantiations throughout your program.