0% found this document useful (0 votes)
10 views

Lec12. Templates

The document discusses C++ templates and how they allow for very general definitions of functions and classes by using type names as parameters instead of actual types. Templates provide another form of polymorphism and allow writing algorithms in a general way that can apply to variables of any type.

Uploaded by

Majd AL Kawaas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lec12. Templates

The document discusses C++ templates and how they allow for very general definitions of functions and classes by using type names as parameters instead of actual types. Templates provide another form of polymorphism and allow writing algorithms in a general way that can apply to variables of any type.

Uploaded by

Majd AL Kawaas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Chapter 16

Templates

Copyright © 2017 Pearson Education, Ltd.


All rights reserved.
Introduction
• C++ templates
– Allow very "general" definitions for functions and classes
– Type names are "parameters" instead of actual types
– Precise definition determined at run-time
– another sort of polymorphism

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 16-2


Function Templates void swapValues(int& var1, int& var2){
int temp;
temp = var1;
• Recall function swapValues: var1 = var2;
var2 = temp;
}
– Applies only to int variables
void swapValues(char& var1, char& var2){
• Can overload function for chars: char temp;
temp = var1;
var1 = var2;
var2 = temp;
}
– But notice, code is nearly identical! only difference is type used in 3 places
• would code work for any type?
template <class T>
• Function template : void swapValues(T& var1, T& var2){
T temp;
– "swap values" of any type variables temp = var1;
var1 = var2;
– First line called "template prefix" var2 = temp;
• Tells compiler what’s coming is "template" }

• And that T is a type parameter

• Calling a Function Template: swapValues(int1, int2);


– C++ compiler “ auto generates" function definition for two int parameters
using template (Likewise for all other types: Needn’t do anything special“)
16-3
Template Prefix and function definition
• template <class T>
– In this usage, "class" means "type", or "classification"
– C++ allows keyword "typename" but most use "class" anyway
– T can be replaced by any type
• Predefined or user-defined (like a C++ class type)
• Note: can use other than "T", but T is "traditional" usage
– T used like any other type in function definition body.
• swapValues() function template is actually large "collection"
of definitions! (a definition for each possible type)
• Compiler only generates definitions when required
– But it’s "as if" you’d defined for all types
• Write one definition  works for all types that might be needed

16-4
//Program to demonstrate a function template.
#include <iostream>
using namespace std;
//Interchanges the values of variable1 and variable2.
//The assignment operator must work for the type T.
template<class T>
void swapValues(T& variable1, T& variable2){
T temp;
temp = variable1;
variable1 = variable2;
variable2 = temp;
}
int main( ){
int integer1 = 1, integer2 = 2;
cout << "Original integer values are " << integer1 << " " << integer2 <<
endl;
swapValues(integer1, integer2);
cout << "Swapped integer values are "<< integer1 << " " << integer2 <<
endl;
char symbol1 = 'A', symbol2 = 'B';
cout << "Original character values are: "
<< symbol1 << " " << symbol2 << endl;
swapValues(symbol1, symbol2);
cout << "Swapped character values are: "<< symbol1 << " " << symbol2 <<
endl; Original integer values are: 1 2
return 0;
Swapped integer values are: 2 1
}
Original character values are: A B 16-5
Swapped character values are: B A
Another Function Template
• Declaration/prototype: Template<class T>
void showStuff(int stuff1, T stuff2, T stuff3);

• Definition: template<class T>


void showStuff(int stuff1, T stuff2, T stuff3){
cout << stuff1 << endl Displays:
<< stuff2 << endl 2
<< stuff3 << endl;
} 3.3
4.4
• Consider function call: showStuff(2, 3.3, 4.4);
– Compiler generates function definition
• Replaces T with double since second parameter is type double

• Defining Templates Strategies


– Develop function normally
• Using actual data types
– Completely debug "ordinary" function then convert to template

16-6
Algorithm Abstraction
• Refers to implementing templates
• Express algorithms in "general" way:
– Algorithm applies to variables of any type
– Ignore incidental detail
– Concentrate on substantive parts of algorithm
• Function templates are one way C++ supports algorithm abstraction

Compiler Complications
• Have function declarations and definitions separate
• Place template function definition in file where invoked
– Many compilers require it appear 1st
– Often we #include all template definitions
16-7
//Demonstrates a template function that implements
//a generic version of the selection sort algorithm.
#include <iostream> Algorithm
using std::cout;
using std::endl;
abstraction
template<class T> example
void sort(T a[], int numberUsed);
//Precondition: numberUsed <= declared size of the array a. sort.cpp
//The array elements a[0] through a[numberUsed - 1] have values.
//The assignment and < operator work for values of type T.
//Postcondition: The values of a[0] through a[numberUsed - 1] have
//been rearranged so that a[0] <= a[1] <=... <= a[numberUsed - 1].

template<class T>
void swapValues(T& variable1, T& variable2);
//Interchanges the values of variable1 and variable2.
//The assignment operator must work correctly for the type T.

template<class T>
int indexOfSmallest( const T a[], int startIndex, int numberUsed);
//Precondition: 0 <= startIndex < numberUsed. Array elements have values.
//The assignment and < operator work for values of type T.
//Returns the index i such that a[i] is the smallest of the values
//a[startIndex], a[startIndex + 1],..., a[numberUsed - 1].

16-8
#include "sort.cpp"
int main( ){ Algorithm
int i, a[10] = {9, 8, 7, 6, 5, 1, 2, 3, 0, 4};
cout << "Unsorted integers:\n"; abstraction
for (i = 0; i < 10; i++) cout << a[i] << " ";
cout << endl;
example
sort(a, 10); sort.cpp
cout << "In sorted order the integers are:\n";
for (i = 0; i < 10; i++) cout << a[i] << " ";
cout << endl;
double b[5] = {5.5, 4.4, 1.1, 3.3, 2.2};
cout << "Unsorted doubles:\n";
for (i = 0; i < 5; i++) cout << b[i] << " ";
cout << endl;
sort(b, 5);
cout << "In sorted order the doubles are:\n";
for (i = 0; i < 5; i++) cout << b[i] << " ";
cout << endl;
char c[7] = {'G', 'E', 'N', 'E', 'R', 'I', 'C'};
cout << "Unsorted characters:\n";
for (i = 0; i < 7; i++) cout << c[i] << " ";
cout << endl;
sort(c, 7);
cout << "In sorted order the characters are:\n";
for (i = 0; i < 7; i++) cout << c[i] << " ";
cout << endl;
16-9
return 0;
// This is the file sort.cpp. Algorithm abstraction example
template<class T>
void sort(T a[], int numberUsed) { sort.cpp
int indexOfNextSmallest;
for ( int index = 0; index < numberUsed - 1; index++){
//Place the correct value in a[index]:
indexOfNextSmallest = indexOfSmallest(a, index, numberUsed);
swapValues(a[index], a[indexOfNextSmallest]);
//a[0] <= a[1] <=...<= a[index] are the smallest of the original
//array elements. The rest of the elements are in the remaining
//positions.
}
}
template<class T>
void swapValues(T& var1, T& var2){
T temp;
temp = var1;
var1 = var2;
var2 = temp;
}
template<class T>
int indexOfSmallest( const T a[ ], int startIndex, int numberUsed) {
T min = a[startIndex];
int indexOfMin = startIndex;
for ( int index = startIndex + 1; index < numberUsed; index++)
if (a[index] < min){
min = a[index];
indexOfMin = index; //min is the smallest of a[startIndex] through a[index] .
}
return indexOfMin;
} 16-10
Class Templates
• Can also "generalize" classes template<class T>
– Can also apply to class definition
– All instances of "T" in class definition replaced by type parameter
– Just like for function templates!

template<class T> template<class T>


class Pair { Pair<T>::Pair(T firstVal, T secondVal) {
public: first = firstVal;
Pair(); second = secondVal;
Pair(T firstVal, T }
secondVal); template<class T>
void setFirst(T newVal); void Pair<T>::setFirst(T newVal){
void setSecond(T newVal); first = newVal;
T getFirst() const; }
T getSecond() const; template<class T>
private: T Pair<T>::getFirst(){
T first; T second; return first;
}; }

• Each definition requires template prefix before it


• Class name before :: is "Pair<T>“ and Not just "Pair"
• But constructor name is just "Pair"
• Destructor name is also just "~Pair" 16-11
More on class templates
• Objects of class have "pair" of values of Pair<int> score;
type T Pair<char> seats;
score.setFirst(3);
• Can then declare objects and use them score.setSecond(0);
like any other objects
• Class templates as parameters
– Consider: int addUP(const Pair<int>& the Pair);
• The type (int) is supplied to be used for T in defining this class type parameter
• It "happens" to be call-by-reference here
– Again: template types can be used anywhere standard types can
• Class templates within function templates
– Rather than defining new overload:
template<class T>
T addUp(const Pair<T>& the Pair);
//Precondition: Operator + is defined for values of type T
//Returns sum of two values in thePair
16-12
– Function now applies to all kinds of numbers
Predefined Template Classes and Type Definition
• Recall vector class : it’s a template class!
• Another: basic_string template class
– basic_string defined in library <string>
– Deals with strings of "any-type" elements
– e.g.,
basic_string<char> works for char’s
basic_string<double> works for doubles
basic_string<YourClass> works for YourClass objects
• Type Definitions: can define new "class type name"
– Example: typedef Pair<int> PairOfInt;
– Name "PairOfInt" now used to declare objects of type Pair<int>:
PairOfInt pair1, pair2;
– Name can also be used as parameter, or anywhere else type name allowed

You might also like