- Asked 2/10
- 2070 Asar · 2 marks
- 2070 Chaitra · 4 marks
Importance of function template
Short answer
Function templates allow one generic function to work with any type, avoiding multiple overloads. They provide code reuse, type safety, and maintainability. Example: template<class T> void swapValues(T& a, T& b){ T temp=a; a=b; b=temp; } works for int, float, etc. Compiler generates type-specific versions.
Explain the importance of function template with suitable example.
A function template defines one generic function for any data type, using a type parameter T. Its importance:
- Code reuse – one definition replaces many overloaded functions that differ only in data type.
- Less effort and fewer errors – logic is written and debugged once.
- Type safety – unlike macros or
void*, the compiler checks types. - Easy maintenance – a change in logic is made in one place.
- No run-time cost – the compiler generates the needed version at compile time.
Example
Without templates we need swap for int, float, char, etc. With a template:
#include <iostream>
using namespace std;
template <class T>
void swapValues(T &a, T &b) {
T temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 9;
float p = 1.5f, q = 2.5f;
swapValues(x, y); // T = int
swapValues(p, q); // T = float
cout << x << " " << y << endl; // 9 5
cout << p << " " << q << endl; // 2.5 1.5
return 0;
}
One function serves both int and float.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Class and function template with syntax · Object Oriented Programming, chapter 9 · asked 4×
- Need of template; function template overloading · Object Oriented Programming, chapter 9
- Function template power(base, exp) · Object Oriented Programming, chapter 9
- Function template: sum and average of array · Object Oriented Programming, chapter 9