Perhaps start with a simple example.
Suppose I had a Point class:
1 2 3 4
|
struct Point {
Point( int x, int y ) : x( x ), y( y ) {}
int x, y;
};
|
and now I want to make another Point class that uses doubles instead of ints. I could:
1 2 3 4
|
struct PointD {
PointD( double x, double y ) : x( x ), y( y ) {}
double x, y;
};
|
Notice that all I did was rename the class (struct) and replace all "int" with "double".
Or, I could use a template:
1 2 3 4 5
|
template< typename T >
struct Point {
Point( T x, T y ) : x( x ), y( y ) {}
T x, y;
};
|
Now Point<int> makes a struct named Point with x and y defined as int, and
Point<double> makes a struct named Point with x and y defined as double.
This is all templates really are.
If I want to move the implementation of the constructor outside the class
(struct), then I write it like:
1 2 3 4 5 6 7 8
|
template< typename T >
struct Point {
Point( T x, T y );
T x, y;
};
template< typename T >
Point<T>::Point( T x, T y ) : x( x ), y( y ) {}
|