Mail Archives: djgpp/1997/06/12/02:20:17
Peter Palotas wrote:
>
> I have been wondering for quite some time what templates are. I have seen
> in some headerfiles in STL (I think) something like Class foo<t> and now I
> am wondering what this is. I would be very grateful if someone could tell
> me where I could read about this stuff, or just tell me what it is and how
> it can be used.
Templates provide a way of passing datatypes as parameters in C++.
Consider the simple function sum() below, that takes two ints as
parameters and returns their sum:
int sum(int x, int y)
{
return x+y;
}
Using a template to generalize this function to handle any class with +
and copy-constructor functionality:
template <class T>
T better_sum(T x, T y)
{
return x+y;
}
This template function is called like a regular function, except that it
can take any single datatype (class) T for both parameters, providing
that +/copy functionality exists for T. Please note that in-built c
datatypes have such functionality (float, int, unsigned, char, etc.),
but classes must either inherit it, or provide new operator+() and
copy-constructor definitions.
example:
#include <iostream.h>
#include <_string.h>
template <class T> T better_sum(T, T);
void main();
template <class T> T better_sum(T x, T y)
{
return x+y;
}
void main()
{
float a, b = 1.0, c = 1.0;
a = better_sum(b, c);
cout << a << endl;
int d, e = 1, f = 1;
d = better_sum(e, f);
cout << d << endl;
String g, h = "hel", i = "lo";
g = better_sum(h, i);
cout << g << endl;
}
Template classes (not functions) are utilized a little differently, but
with the same idea of automatically accounting for many different
datatypes. To create an instance of a class decclared thus,
template <class T> class Foo
{
.
.
.
};
requires provision of a datatype parameter list. i.e.
Foo<float> a;
Foo<int> a;
Foo<String> a;
etc.
The functionality required of class T is determined by the
implementation of Foo<class T>.
- Raw text -