- 67 Views
- Uploaded on
- Presentation posted in: General

Chapter 17

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Chapter 17

Templates

Algorithms in which the actions or steps are defined, but the data types of the items being manipulated are not.

- 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

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 <class T>

void swap (T& v1, T& v2)

{

T temp = v1;

v1 = v2;

v2 = v3;

}

int main ()

{

int i1=1, i2=2;

swap (i1, i2);

char c1=‘a’, c2=‘A’;

swap (c1, c2);

}

- 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 for a pair of values of type T

template <class T>

class Pair

{

public:

Pair();

Pair(T f, T s);

void setElement (intpos, T val);

T getElement (intpos);

private:

T first;

T second;

};

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 (intpos, T val) {

if (pos == 1)

first = val;

else

second = val;

}

template <class T>

T Pair<T>::getElement (intpos) {

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);

}

- 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.