The second solution requires more planning, but it has the benefit of reduced compile time and link time for large projects.
In this approach we only include ll.h whenever a template class based on LinkedList<T> is required. Then, we collect all the template classes, and instantiate all of them in a particular source file (ll_instances.cc), as illustrated in listing 7.
Listing 7: | templateclassinstantiation |
The statement template class LinkedList<int>; (and its siblings) specifically ask the compiler to emit code for the template class.
Because there is only one ll_instances.cc, each template class is instantiated only once. As a result, the compiler only generates (and optimizes) the template class instances onces. All the other files are merely referring to methods that are generated from ll_instances.cc.
This approach may sound primitive and labor intensive. However, it gives the developers complete control over template class instantiation. This approach is also well suited to large projects, where the time to set up and maintain ll_instances.cc is minimal compared to the compile time and link time penalty of generating duplicate instances as described in the previous section.