Object Oriented Programming - Old Questions

10. Create a function called swaps() that interchanges the values of the two arguments sent to it (pass these arguments by reference).  Make the function into a template, so it can be used with all numerical data types (char, int, float, and so on). Write a main() program to exercise the function with several types.

5 marks | Asked in 2075

#include<iostream>

using namespace std;

template <class T>

void swaps(T &a,T &b)      //Function Template

{

    T temp=a;

    a=b;

    b=temp;

}

int main()

{

    int x1=5,y1=9;

    float x2=3.5,y2=6.5;

    cout<<"Before Swap:"<<endl;

    cout<<"x1="<<x1<<"y1="<<y1<<endl;

    cout<<"x2="<<x2<<"y2="<<y2<<endl;

    swaps(x1,y1);

    swaps(x2,y2);

    cout<<"After Swap:"<<endl;

    cout<<"x1="<<x1<<"y1="<<y1<<endl;

    cout<<"x2="<<x2<<"y2="<<y2<<endl;

    return 0;

}