Sams Teach Yourself C++ in 21 Days

(singke) #1
[5] 50
[6] 60
[7] 70
[8] 80
[9] 90
On line 43, the function template operator<<()is declared to be a friend of the
Arrayclass template. Because operator<<()is implemented as a template func-
tion, every instance of this parameterized array type automatically has an operator<<().
The implementation for this operator starts on line 50. Using a simple loop on lines 53
and 54, every member of an array is called in turn. This only works if an operator<<()
is defined for every type of object stored in the array.
It is worth pointing out that this listing also required that the overloading of operator[].
You can see on line 37 that this was done using the template type as well.

Using Template Items ..........................................................................................


You can treat template items as you would any other type. You can pass them as parame-
ters, either by reference or by value, and you can return them as the return values of
functions, also by value or by reference. Listing 19.5 demonstrates how to pass template
objects.

LISTING19.5 Passing Template Objects to and from Functions
0: //Listing 19.5 Passing Template Objects to and from Functions
1: #include <iostream>
2: using namespace std;
3:
4: const int DefaultSize = 10;
5:
6: // A trivial class for adding to arrays
7: class Animal
8: {
9: public:
10: // constructors
11: Animal(int);
12: Animal();
13: ~Animal();
14:
15: // accessors
16: int GetWeight() const { return itsWeight; }
17: void SetWeight(int theWeight) { itsWeight = theWeight; }
18:
19: // friend operators
20: friend ostream& operator<< (ostream&, const Animal&);

678 Day 19


ANALYSIS
Free download pdf