16.1.1. Defining a Function Template
The following is a template version of compare:
// implement strcmp-like generic compare function
// returns 0 if the values are equal, 1 if v1 is larger , -1 if v1 is smaller
template <typename T>
int compare(const T &v1, const T &v2)
{
if (v1 < v2) return -1;
if (v2 < v1) return 1;
return 0;
}
A template definition starts with the keyword templatefollowed by a template parameter list , which is a comma-separated list of one or more template parameters bracketed by the lessthan (<) and greater-than (>) tokens.
Note:The template parameter list cannot be empty.
Template Parameter List
Analogously, template parameters represent types or values we can use in the definition of a class or function. For example, our comparefunction declares one type parameter named T. Inside compare, we can use the name T to refer to a type. Which actual type Trepresents is determined by the compiler based on how the function is used.
A template parameter can be a type parameter , which represents a type, or a nontype parameter , which represents a constant expression. A nontype parameter is declared following a type specifier. We'll see more about nontype parameters in Section 16.1.5. A type parameter is defined following the keyword class or typename. For example, class T is a type parameter named T. There is no difference between classand typenamein this context.
Using a Function Template
When we use a function template, the compiler infers what template argument(s) to bind to the template parameter(s). Once the compiler determines the actual template argument(s), it instantiates an instance of the function template for us. Essentially, the compiler figures out what type to use in place of each type parameter and what value to use in place of each nontype parameter. Having deduced the actual template arguments, it generates and compiles a version of the function using those arguments in place of the corresponding template parameters. The compiler takes on the tedium of (re)writing the function for each type we use.
int main ()
{
// T is int;
// compiler instantiates int compare(const int&, const int&)
cout << compare(1, 0) << endl;
// T is string;
// compiler instantiates int compare(const string&, const string&)
string s1 = "hi", s2 = "world";
cout << compare(s1, s2) << endl;
return 0;
}
the compiler will instantiate two different versions of compare. The compiler will create one version that replaces Tby intand a second version that uses stringin place of T.
inlineFunction Templates
A function template can be declared inlinein the same way as a nontemplate function. The specifier is placed following the template parameter list and before the return type. It is not placed in front of the template keyword.
// ok: inline specifier follows template parameter list
template <typename T> inline T min(const T&, const T&);
// error: incorrect placement of inline specifier
inline template <typename T> T min(const T&, const T&);