Imagine writing a function. Here's one:
1 2 3 4
|
int addTwoNumbers (int a, int b)
{
return (a+b);
}
|
Now imagine that we want to have the same function, for a different type.
1 2 3 4
|
double addTwoNumbers (double a, double b)
{
return (a+b);
}
|
The only difference between the two functions is the types. If only there was some way to tell the compiler that we want functions like this:
1 2 3 4
|
SOMETYPE addTwoNumbers (SOMETYPE a, SOMETYPE b)
{
return (a+b);
}
|
and that the compiler will do the rest for us. This is what templates are for.
You simply write the function as normal, but on the front you put
template <class SOMETYPE>
and in your code you write the type that the compiler has to fill in for you as
SOMETYPE
,
so you get this:
1 2 3 4 5
|
template <class SOMETYPE>
SOMETYPE addTwoNumbers (SOMETYPE a, SOMETYPE b)
{
return (a+b);
}
|
You can put whatever you like for SOMETYPE. Lots of people like to use T, like this:
1 2 3 4 5
|
template <class T>
T addTwoNumbers (T a, T b)
{
return (a+b);
}
|
Then, every time we try to use a function called
addTwoNumbers
, like this:
addTwoNumber(7,5);
or
addTwoNumbers(someDoubleValue1, someDoubleValue2);
or
addTwoNumbers(someFloatValue1, someFloatValue2);
the compiler will make that function for us, using the template as a guide.