Sams Teach Yourself C++ in 21 Days

(singke) #1
template class and defining a template member function. First, you indicate that your
function is a template, and then you use the template parameter where you otherwise
would have used a type or class name:
template <class T>
void MyTemplateFunction(Array<T>&); // ok
In this example, the function MyTemplateFunction()is declared to be a template func-
tion by the declaration on the top line. Note that template functions can have any name,
the same as other functions can.
Template functions can also take instances of the template in addition to the parameter-
ized form. The following is an example:
template <class T>
void MyOtherFunction(Array<T>&, Array<int>&); // ok
Note that this function takes two arrays: a parameterized array and an array of integers.
The former can be an array of any object, but the latter is always an array of integers. A
little bit later today, you will see a template function in action.

Templates and Friends ........................................................................................


You learned about friends on Day 16, “Advanced Inheritance.” Template classes can
declare three types of friends:


  • A nontemplate friend class or function

  • A general template friend class or function

  • A type-specific template friend class or function
    The following sections cover the first two of these.


Nontemplate Friend Classes and Functions ..................................................


It is possible to declare any class or function to be a friend to your template class. Each
instance of the class will treat the friend properly, as if the declaration of friendship had
been made in that particular instance.
Listing 19.3 adds a trivial friend function,Intrude(), to the template definition of the
Arrayclass. The driver program then invokes Intrude().
Because Intrude()is a friend, it can then access the private data of the Array. Because
Intrude()is not a template function, it can only be passed Arrays of type int.

670 Day 19

Free download pdf