close
First , let us see the follow two functions :
int
max(
int
nX,
int
nY)
{
return
(nX > nY) ? nX : nY;
}
double
max(
double
dX,
double
dY)
{
return
(dX > dY) ? dX : dY;
}
these two functions are almost the same , beside the parameter type and return type.
although function overloading can help us deal with the problem which the parameter type is different ,
but it can not deal with different return type.
So , that is why we need function template.
In C++, function templates are functions that serve as a pattern for creating other similar functions.
first , we need to make a function template declaration :
template
<
typename
Type>
// this is the template parameter declaration
Type max(Type tX, Type tY)
{
return
(tX > tY) ? tX : tY;
}
then we can start using the function template.
int
nValue = max(3, 7);
// returns 7
double
dValue = max(6.34, 18.523);
// returns 18.523
char
chValue = max(
'a'
,
'6'
);
// returns 'a'
ref : http://www.learncpp.com/cpp-tutorial/141-function-templates/
全站熱搜