Templates 665
19
Implementing the Template ............................................................................
After you have a template defined, you’ll want to use it. The full implementation of the
Arraytemplate class requires implementation of the copy constructor,operator=, and so
forth. Listing 19.2 provides the code for your Arraytemplate as well as a simple driver
program that uses the template.
member functions and the necessary member function definitions can be
split between a header and a .cppfile, templates require both to be in
either a header or .cppfile. If you are sharing the template with other parts
of your project, it is common to either define the member function inline to
the template class declaration, or to define them below the class declaration
in the header file.
Some older compilers do not support templates. Templates are, however,
part of the ANSI C++ standard. All major compiler vendors support tem-
plates in their current versions. If you have a very old compiler, you won’t be
able to compile and run the exercises in today’s lesson. It’s still a good idea
to read through the entire lesson, however, and return to this material
when you upgrade your compiler.
NOTE
LISTING19.2 The Implementation of the Template Array
0: //Listing 19.2 The Implementation of the Template Array
1: #include <iostream>
2:
3: const int DefaultSize = 10;
4:
5: // declare a simple Animal class so that we can
6: // create an array of animals
7:
8: class Animal
9: {
10: public:
11: Animal(int);
12: Animal();
13: ~Animal() {}
14: int GetWeight() const { return itsWeight; }
15: void Display() const { std::cout << itsWeight; }
16: private:
17: int itsWeight;
18: };