In C++, we can write a function to operate on generic types. If we want to have the same function for different data types like, int, double, string, etc., we can have only one template function instead of having different functions with different names or multiple overloaded functions.
#include <iostream>
using namespace std;
template <typename T>
T add(T a, T b) {
return (a + b);
}
int main() {
cout << "Adding two integers 4 and 5: " << add(4, 5) << endl;
cout << "Adding two doubles 4.1 and 5.1: " << add(4.1, 5.1) << endl;
cout << "Adding two strings \"QnA\" and \" Plus\": " << add(string("QnA"), string(" Plus")) << endl;
return 0;
}
$ g++ -o test test.cpp
$ ./test
Adding two integers 4 and 5: 9
Adding two doubles 4.1 and 5.1: 9.2
Adding two strings "QnA" and " Plus": QnA Plus
In this example, we have a template function add(). The same function was used to add integers, doubles and strings.
This feature helps us reduce code size significantly. It increases code elegance and maintainability.