Class
templates
We also have the possibility to write class templates, so
that a class can have members that use template parameters as types. For example:
1
2 3 4 5 6 7 8 9 |
template <class T>
class
mypair {
T values [2];
public:
mypair (T first, T second)
{
values[0]=first; values[1]=second;
}
};
|
The class that we have just defined serves to store two elements of any valid type. For example, if we wanted to declare an object of this class to store two integer values of type int with the values 115 and 36 we would write:
mypair<int>
myobject (115, 36);
|
this same class would also be used to create an object to store any other type:
mypair<double>
myfloats (3.0, 2.18);
|
The only member function in the previous class template has been defined inline within the class declaration itself. In case that we define a function member outside the declaration of the class template, we must always precede that definition with the template <...> prefix:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// class templates
#include <iostream>
using namespace std;
template <class T>
class
mypair {
T a, b;
public:
mypair (T first, T second)
{a=first; b=second;}
T getmax ();
};
template <class T>
T mypair<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}
int
main () {
mypair <int> myobject (100, 75);
cout << myobject.getmax();
return 0;
}
|
100
|
Notice the syntax of the definition of member function getmax:
1
2 |
template <class T>
T mypair<T>::getmax ()
|
Confused by so many T's? There are three T's in this declaration: The first one is the template parameter. The second T refers to the type returned by the function. And the third T (the one between angle brackets) is also a requirement: It specifies that this function's template parameter is also the class template parameter.
0 komentar:
Post a Comment