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) { }


Example: How to swap two numbers using function templates in C++

Run it Now
#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 << "\nBefore Swap :\n";

    cout << "\nx value is :" << x;
    cout << "\ny value is :" << y;

    Swap(x, y);

    cout << "\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