C++ Template Syntax
To declare a template function or class in C++ you must preceed the definition with the following:
template<class T>
The following items describe the syntax of declaring and using templates:
- The key word template warns the reader that what is being declared or defined
is a template function or a template class as opposed to an ordinary function or class.
- The angle brackets <> that enclose the formal parameter lists indicate the
parameters the template function or class depends upon. They serve the same purpose
as () to enclose a formal argument list for a function.
- The word class tells that the kind of parameter is a type.
- The T is a formal name for the type much the same as formal function argument names are
part of the definition of a function. The symbol T is not a keyword. (We could
have used template<class Fred> just as well, replacing T with Fred
everywhere in the template definition.) Most C++ programmers use T as a matter
of simplicity and style.
- To use a function template we merely call the function, passing appropriate arguments.
In your code it looks just like a normal function call. C++ looks at the call and
the function template and generates a template function using the appropriate types.
- To create an instance of a template class requires providing the type of the
formal parameter. For example, if we have a template class called Stack, we would
create an instance of Stack for floats by saying: Stack<float&bt; float_stack;
Now float_stack is an instance of a Stack<float>.
- Member functions of a template class are function templates. The definition of a member
functions must start with the template prefix, template<class T>. Member functions
defined outside the class definition (external rather than inline) must have the class name followed
by the parameter. Thus a member function of class Stack would be externally defined by
Stack<T>::Member().
- Constructor and destructor definitions do not require the duplication of the <T>
in their names. That is, a constructor for template class Stack would be designated by:
Stack<T>::Stack().