Strange they start with templates in classes...
To be honest, I'm not really familiar with templates either, but I will try to explain it to you by a normal funcion that does the same thing as your class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <iostream>
using namespace std;
template <typename T>
inline T const& max (T const& a, T const& b)
{
// if a < b then use b else use a
return a<b?b:a;
}
int main(){
double a=3,2;
double b=4,7;
cout<<max(a,b);
int c=9;
int d=1242;
cout<<max(c,d);
cin.ignore();
return 0;
}
|
As you can see, whe create a function that returns the highest value of two variables. Nothing strange about that. But in a normal function, you would declare the type of the return value and the two parameters. Here we first create a template "T" and then use that as type.
This means that we can use every datatype (including self-defined classes) that support the operations we do with them inside the function, in this case ">".
So whe call the function, first with two doubles, then with two integers. You could also call it with strings and floats, etc. etc.
For so far template functions. Now about your code: the reason that you have to declare T twice is because it belongs to the fowolling function (or class).
I dont know or you understand this:
retval = a>b? a : b;
The "?" is an operator with three operants. The first, on the left ("a>b"), gives true or false. If it gives true, the second ("a") will be 'exucuted', in this case stored into retval. If the first operant holds false, the tird operand will be executed ("b").\
mypair <int> myobject (100, 75);
Here we create an object of our templateclass, using the self-defined constructor. With <int> the compiler is explecitly told that T is an integer. If you didnt wrote this, T would become of type integer inplecitly the first time you use it (when you use 100 as argument).
Hope this helps. If you got any questions left, please ask.