The final construct we need to look at is templates. Templates specify recipes for the definition of individual functions or classes. They play an important part in the design of generic libraries and we will be using them when we begin looking at the STL in a future class. For now, we will consider a simple templated function and templated class to refresh your memories.
Consider the function maximal() from Main and Savitch
double maximal(double x, double y)
{
if (x>y) {
return x;
} else {
return y;
}
}
We could define the exact same function body for x and y integers
int maximal(int x, int y)
{
if (x>y) {
return x;
} else {
return y;
}
}
or for any type where the comparison operator > is defined
including our string type. When the behavior of a routine
can be separated from the type of the operands, a template
function can be used to specify a recipe for how to implement that
operand that is independent of the type.
template <class T>
T maximal(T x, T y)
{
if (x>y) {
return x;
} else {
return y;
}
}
Examples -
double x, y;
x=7.2; y=5.3;
cout << maximal(x,y) << endl;
int a(4), b(3);
cout << maximal(b, a) << endl;
string s("happy"), t("birthday"), u("anniversary");
cout << maximal(s, t) << " " << maximal(t, u) << endl;
Consider the following class in file maxsofar.h:
class maxsofar
{
public:
maxsofar(int seed):maxval(seed){}
void check(int val);
int max() const {return maxval;}
private:
int maxval;
};
with implementation in file maxsofar.cpp
void maxsofar::check(int val)
{
if (val>maxval) {
maxval = val;
}
}
The functionality of this class is appropriate to any type supporting copy construction, assignment and > allowing us to write
template <class T>
class maxsofar
{
public:
maxsofar(T seed):maxval(seed){}
void check(T val);
T max() const {return maxval;}
private:
T maxval;
};
#include "maxsofar.def"
with implementation in file maxsofar.def
template <class T>
void maxsofar<T>::check(T val)
{
if (val>maxval) {
maxval = val;
}
}
Examples -
string hello("Hello");
string world("world");
maxsofar<string> str(hello);
cout << str.max() << " ";
str.check(world);
cout << str.max() << endl;
maxsofar<int> x(5);
cout << x.max() << endl;
x.check(2);
cout << x.max() << endl;
x.check(7);
cout << x.max() << endl;
Class Exercise -
Write a template function to swap two values, i.e.
char x('c');
char y('d');
swap(x,y);
cout << x << ' ' << y << endl;
would output
d c
Write a short main to read in 10 strings and print out the maximum string read.