Posted by eerttraw on 1999-03-24
A direct quote from C++ Primer Plus Second Edition by Stephen Prata:
"Earlier we defined a function that swapped 2 int values. Suppose you
were to swap 2 double values instead. One approach is to duplicate the
original code, but replace each int with double. If you needed to swap 2
char values, you could use the same technique again. Still, it's wasteful
of your valuable time to have to make these petty changes, and there's
always the possibility of making an error. If you make the changes by hand,
you might overlook and int. If you do a global search-and-replace, you may
do something such as converting
int integer;
to the following:
double doubleeger;
C++'s function template capability automates the process, saving you time
and providing greater reliability.
Function templates let you define a function in terms of some arbitrary
type. For instance, we can set up a swapping template like this:
template <class Any>
void swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
};
The first line specifies that we are setting up a template and that we're
naming the arbitrary type Anuy. The keywords template and class are
obligatory, as are the angle brackets."
Since you do not have great familiarity with C++, you may wish to consider
buying a book like this one. If money is a concern, borrow it from the
public library.
-Nels Hansen
> Can someone offer an explanation of C++ templates and how they would be
> used, and maybe why I would need to use them?
>
> Thanx!!
>
> --
> From: Frank Hale
> Email: frankhale@xxxxxxxx.xxx.xxx
> ICQ: 7205161
> Website: http://www.franksstuff.com
>
> "Lets have a party Linux kernel 2.2.4 is out, woohoo!!!"
Previous post | Next post | Timeline | Home