Chapter 17

Chapter 17
Templates
Generic Algorithms
Algorithms in which the actions or steps are
defined, but the data types of the items
being manipulated are not.
Examples Of Generic Algorithm
• Swap the values of two variables of the same
data types
• Find the index of the smallest value in an
array.
• Pair up 2 values
• Linked list
Overloading functions for Generic
Algorithms
void swap (char& v1, char& v2)
{
char temp = v1;
v1 = v2;
v2 = v3;
}
void swap (int& v1, int& v2)
{
int temp = v1;
v1 = v2;
v2 = v3;
}
void double (double & v1, double & v2)
{
double temp = v1;
v1 = v2;
v2 = v3;
}
void swap (CAny& v1, CAny& v2)
{
CAny temp = v1;
v1 = v2;
v2 = v3;
}
Template for Functions
template <class T>
void swap (T& v1, T& v2)
{
T temp = v1;
v1 = v2;
v2 = temp;
}
int main ()
{
int i1=1, i2=2;
swap (i1, i2);
char c1=‘a’, c2=‘A’;
swap (c1, c2);
}
Template Function Notes
• The words template <class T> tell the compiler
this is a template for a generic data type T and
that T is the parametized type which can be
replaced by a defined data type.
• T must have all of the operations used in the
template function.
int a[5], b[5];
… // Some code to fill up arrays
swap (a, b); // NO! There is no assignment operator for arrays
Class Template
//Class template for a pair of values of type T
template <class T>
class Pair
{
public:
Pair();
Pair(T f, T s);
void setElement (int pos, T val);
T getElement (int pos);
private:
T first;
T second;
};
Class Template (cont.)
template <class T>
Pair<T>::Pair() {}
template <class T>
Pair<T>::Pair(T f, T s) {
first = f;
second = s;
}
template <class T>
void Pair<T>::setElement (int pos, T val) {
if (pos == 1)
first = val;
else
second = val;
}
template <class T>
T Pair<T>::getElement (int pos) {
if (pos == 1)
return first;
else
return second;
}
void main ()
{
Pair<int> scores;
Pair<char>seats(‘A’, ‘B’);
score.setElement(1, 3);
score.setElement(2, 5);
char mySeat;
mySeat=seats.getElement(1);
}
Class Template Notes
• The words template <class T> tell the compiler this is
a template for a generic data type T and that T is the
parametized type which can be replaced by a defined
data type.
• T is used as a type in all function definitions or
parameters of the class template.
• You can use typedef to improve readability.
typedef Pairs<int> PairsOfInt;
then declare PairsOfInt score;
• Type T is specialized by giving a type argument to the
class name in place of the T.