A significant benefit of object-oriented programming is the reusability of code which eliminates redundant coding. An important feature of C++ is called templates. Templates support generic programming, which allows to development of reusable software components such as functions, classes, etc., supporting different data types in a single framework.
A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter. The templates declared for functions are called function templates and those declared for classes are called class templates.
This article focuses on discussing how to use a function template to swap two numbers in C++.
Function Templates
There are several functions of considerable importance which have to be used frequently with different data types. The limitation of such functions is that they operate only on a particular data type. It can be overcome by defining that function as a function template or a generic function. A function template specifies how an individual function can be constructed.
Syntax:
template <class T, …… >
returntype FuncName (arguments)
{
// body of template function
………..
…………
}
Below is the C++ program to implement the function templates to swap two numbers.
// C++ program to implement // function templates #include <iostream> using namespace std;
// Function template to swap // two numbers template < class T>
int swap_numbers(T& x, T& y)
{ T t;
t = x;
x = y;
y = t;
return 0;
} // Driver code int main()
{ int a, b;
a = 10, b = 20;
// Invoking the swap()
swap_numbers(a, b);
cout << a << " " << b << endl;
return 0;
} |
20 10