Problem:
Using templates can lead to code bloat: binaries with replicated (or almost replicated) code, data, or both.
The result can be source code that looks fit and trim, yet object code that’s fat and flabby. Fat and flabby is rarely fashionable, so you need to know how to avoid such binary bombast.
Solution:
Your primary tool has the imposing name commonality and variability analysis.
Non-template code
When you’re writing a function and you realize that some part of the function’s implementation is essentially the same as another function’s implementation, do you just replicate the code?
Of course not. You factor the common code out of the two functions, put it into a third function, and have both of the other functions call the new one.
Similarly, if you’re writing a class and you realize that some parts of the class are the same as parts of another class, you don’t replicate the common parts. Instead, you move the common parts to a new class, then you use inheritance or composition (see Items 32, 38, and 39) to give the original classes access to the common features.
Template code
In non-template code, replication is explicit: you can see that there’s duplication between two functions or two classes. In template code, replication is implicit: there’s only one copy of the template source code, so you have to train yourself to sense the replication that may take place when a template is instantiated multiple times.
Example:
template<typename T, // template for n x n matrices of
std::size_t n> // objects of type T; see below for info
class SquareMatrix {
// on the size_t parameter
public:
...
void invert(); // invert the matrix in place
};
SquareMatrix<double, 5> sm1;
...
sm1.invert(); // call SquareMatrix<double, 5>::invert
SquareMatrix<double, 10> sm2;
.