We have used three kinds of absolute value function: abs, labs, and fabs.
These functions differ only in the type of their argument. It might be better to have a function template for the absolute value function. Give a function template for an absolute value function called absolute. The template will apply only to types for which < is defined, for which the unary negation operator is defined, and for which the constant 0 can be used in a comparison with a value of that type.
Function Template
The function definition and the function declaration for a function
template are each prefaced with the following:
template<class Type_Parameter>
The function declaration (if used) and definition are the same as any
ordinary function declaration and definition, except that the
Type_Parameter can be used in place of a type.
For example, the following is a function declaration for a function
template:
template<class T>
void show_stuff(int stuff1, T stuff2, T stuff3);
The definition for this function template might be as follows:
template<class T>
void show_stuff(int stuff1, T stuff2, T stuff3)
{
cout << stuff1 << endl
<< stuff2 << endl
}
The function template given in this example is equivalent to having
one function declaration and one function definition for each possible
type name. The type name is substituted for the type parameter (which is
T in the example above). For instance, consider the following function call:
show_stuff(2, 3.3, 4.4);
When this function call is executed, the compiler uses the function
definition obtained by replacing T with the type name double. A
separate definition will be produced for each different type for which you
use the template, but not for any types you do not use. Only one definition
is generated forGive both the function declaration and the function definition for the template.
template<class T>
T absolute(T value);
//Precondition: The expressions x < 0 and − x are defined
//whenever x is of type T.
//Returns the absolute value of its argument.
template<class T>
T absolute(T value)
{
if (value < 0)
return − value;
else
return value;
}