Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - When to use overloaded functions? When to use function templates?
When to use overloaded functions? When to use function templates?
Function overloading refers to the same function name, the same number of parameters, or different parameter types.

Function templates refer to the same function name, the same number of parameters, the same function body, but different parameter types.

From the above definition, function template can be realized, function overload can certainly be realized, and vice versa.

For example, a function that compares the sizes of two variables. Functions can be overloaded for integer variables and double-precision variables.

int compare(int a,int b)

{

If (a>b)

Returns1;

else if(a == b)

Returns 0;

other

return- 1;

}

Int comparison (double a, double b)

{

If (a>b)

Returns1;

else if(a == b)

Returns 0;

other

return- 1;

}

This situation can also be realized by using function templates, because the function bodies of the above two functions are exactly the same.

Int comparison (T a, Tb)

{

If (a>b)

Returns1;

else if(a == b)

Returns 0;

other

return- 1;

}

But obviously it is better to use function templates at this time, because it avoids code duplication. Experience the difference between the two in application ~