Pros and Cons of Templates
Obviously, templates provide enormous benefits. They save time, provide flexibility in using datatypes, and encourage source code reuse. This brings us to the one disadvantage of templates: it is the source code that is reused, not the object code. A declaration for
RWMathVec<double> is compiled separately from
RWMathVec<int>. This means that the two declarations generate different object code for the two classes, which can bloat the executable.
To some extent, this is unavoidable. For example, if you derive your own class from an
RWMathVec<T> , thus forcing it to be parameterized on
T, the compiler builds a separate class and object code for each instantiated type
T. To save code, it is better to recognize points of commonality that do not depend on the actual type, factor them out, and put them into a separate type-independent class which can be compiled once.
We have followed our own advice in the Essential Math Module; for example, vector length is maintained in the class
RWVecView, a base class of
RWMathVec.
RWVecView is not templatized, nor are any of its base classes. We reduce the code bloat by putting only type-dependent code in the
RWMathVec<T>,
RWGenMat<T>, and
RWMathArray<T> classes, and abstracting the rest to nontemplatized base classes.