Template Declarations and Definitions


Examples

The following example demonstrates how a specific version of a class template may be supplied. A specific version is used when available.

template <class T,unsigned rows,unsigned columns> class matrix;
 
class matrix <double,3,3>      // Provides a specific version of templateMatrix.
{                              // This specific version is used in preference
 ...                           // to a generated version - but only for
};                             // 3x3 matrices using type double.
 
matrix<double,4,4> matrixA;  // matrixA == 4x4 matrix - uses template generated definition.
matrix<double,3,3> matrixB;  // matrixB == 3x3 matrix - uses specific version.

The next example is similar to the last except that it is for function templates. Note that providing a specific version of a function template has implications for function overloading resolution.

template<class T> T maximum(T a, T b)   // Definition of function template.
{return a>b ? a : b;};
 
int maximum(int i, int j)               // Specific version of maximum.
{return i>j ? i : j;}
 
double f=1,g=2;
double h = maximum(f,g);    // Generates a function maximum that
                            // accepts two numbers and returns a number.
int i=1,j=2;
int k = maximum(i,j);       // Uses specific version of maximum

char c='a';
int A = 65;
int l = maximum(A,c);       // Uses specific version: int maximum(int i, int j).

The last call would be in error had not a specific version of the function template maximum been supplied. Template functions are generated for a call only when an exact match is made. When a specific version (as shown above) has been defined, it is possible (on some occasions) to use parameter matching to select a suitable function to call, even when an exact match is not available.