Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |
Just as a class template describes a family of classes, a
function template describes a family of functions. The syntax for creating
either type of template is virtually identical, but they differ somewhat in how
they are used. You must always use angle brackets when instantiating class
templates and you must supply all non-default template arguments. However, with
function templates you can often omit the template arguments, and default
template arguments are not even allowed. Consider a typical
implementation of the min( ) function template declared in the <algorithm>
header, which looks something like this:
template<typename T> const T& min(const
T& a, const T& b) {
return (a < b) ? a : b;
}
You could invoke this template by providing the type of the
arguments in angle brackets, just like you do with class templates, as in:
This syntax tells the compiler that a specialization of the min( )
template is needed with int used in place of the parameter T,
whereupon the compiler generates the corresponding code. Following the pattern
of naming the classes generated from class templates, you can think of the name
of the instantiated function as min<int>( ).
Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |