Template Specializations
Sometimes a template with a particular type does not follow general template behavior. For example, let’s say you implement a templatized function:
template<class T> int LessThan(T a, T b) {return a<b;}
If you later call this function with complex arguments, you get a compiler error. For almost all built-in types, however, the LessThan function does work properly, so you could specialize the LessThan function for the complex type as follows:
int LessThan(DComplex a, DComplex b) {return abs(a)<abs(b);}
In all cases except
DComplex, the original
LessThan function is called, but if two
DComplex arguments are given, the specialization is used.
In some cases, specialization can be a powerful tool. For example, we can use specializations of a helper class
rw_numeric_traits to modify the behavior of certain mathematical operations, depending on type. (See
Defining a New Numeric Type.)
Specializations are handled differently from compiler to compiler, and with different degrees of sophistication. For this reason, we keep the number of specializations in the Essential Math Module to a minimum.