What is generic function or template function in C++?

Generic function aka template function is used to define general set of actions which will be performed to a wide range of data. A generic function actually defines the nature of an algorithm. A keyword template is used to create a generic function. A generic function can overload or override itself. Generic functions are used to write reusable codes which can be used in other programs. Thus, the use of generic functions saves a lot of time.

Syntax of generic function:

template <class T> return_type function_name(parameter_list)



Where, T is placeholder for data type.

For Example:

#include <iostream>

using namespace std;

template <class T> void swap(T &i, T &j)


T temp;

temp = i;

i = j;

j = temp;


int main()


int a=5, b=10;

char c=’e’, d=’f';

swap(a, b);

swap(c, d);

cout << “Swapped value of a, b: ” << a << ‘ ‘ << b << ‘\n';

cout << “Swapped value of c, d: ” << c << ‘ ‘ << d << ‘\n';

return 0;



Swapped value of a, b: 10 5

Swapped value of c, d: f e

Leave a Reply