Overloading function templates in C++
- A template is a tool that reduces the efforts in writing the same code as templates can be used at those places.
- A template function can be overloaded either by a non-template function or using an ordinary function template.
Square of 9 is 81 Square of 2.25 is 5.0625
- In the above code, the square is overloaded with different parameters.
- The function square can be overloaded with other arguments too, which requires the same name and different arguments every time.
- To reduce these efforts, C++ has introduced a generic type called function template.
Function Template: The function template has the same syntax as a regular function, but it starts with a keyword template followed by template parameters enclosed inside angular brackets <>.
template <class T>
T functionName(T arguments)
// Function definition
………. …… ….. …….
where, T is template argument accepting different arguments and class is a keyword.
Template Function Overloading:
- The name of the function templates are the same but called with different arguments is known as function template overloading.
- If the function template is with the ordinary template, the name of the function remains the same but the number of parameters differs.
- When a function template is overloaded with a non-template function, the function name remains the same but the function’s arguments are unlike.
Below is the program to illustrate overloading of template function using an explicit function:
Explicitly display: 200 Displaying Template: 12.4 Displaying Template: G