C++ Program to swap two numbers using function templates
In this program, You will learn how to swap two numbers using function templates in C++.
template < class T >
void swap(T &x, T &y) {
//statement
}
Example: How to swap two numbers using function templates in C++
#include<iostream>
using namespace std;
template <class T>
void Swap(T &x, T &y) {
T temp;
temp = x;
x = y;
y = temp;
}
int main() {
int x, y;
cout << "Enter two numbers:";
cin >> x>>y;
cout << "Before Swap:";
cout << "\nx value is:" << x;
cout << "\ny value is:" << y;
Swap(x, y);
cout << "\n\nAfter Function Templates:\n";
cout << "\nx value is:" << x;
cout << "\ny value is:" << y;
return 0;
}
Output:
Enter two numbers:10 20
Before Swap:
x value is:10
y value is:20
After Function Templates:
x value is:20
y value is:10