You probably heard of code bloat
or object bloat
when using templates. It is caused by instanciate too many versions of the same template for different types, causing object file to become very big while source code looks slim. Let’s see an example
1 | template<typename T, std::size_t n> |
If you compile above code and inspect the symbol table, you will find out that two versions of functions are generated, one for size 5 matrix and one for size 10 matrix.
1 | $ nm main.o | c++filt |
A better design will be using private inheritance to share implementation, which is exactly why private inheritance exists(refer to item39).
1 | template<typename T> |
Now if we look at the symbol table again, you will see that the actual implementation of invert
is shared in the version of SquareMatrixBase<double>::invert(unsigned long)
.
1 | $ nm main.o | c++filt |
Code bloat is often an issue when coding in templates and somethimes difficult to predict before you look at object file size. 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.