Template Function in C++

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.

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
0
0