Template Functions in C++

If you want to pass an array object to a function, you must pass a particular instance of the array, not a template. Therefore, if SomeFunction() takes an integer array as a parameter, you may write
void SomeFunction(Array<int>&);    // ok
but you may not write
void SomeFunction(Array<T>&);   // error!
because there is no way to know what a T& is. You also may not write
void SomeFunction(Array &);     // error!
because there is no class Array--only the template and the instances.
To accomplish the more general approach, you must declare a template function.
template <class T>
void MyTemplateFunction(Array<T>&);    // ok
Here the function MyTemplateFunction() is declared to be a template function by the declaration on the top line. Note that template functions can have any name, just as other functions can.
Template functions can also take instances of the template, in addition to the parameterized 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.

Templates and Friends

Template classes can declare three types of friends:
Template Functions in C++ Reviewed by 1000sourcecodes on 23:55 Rating: 5
Powered by Blogger.