Pages

Thursday, February 12, 2015

C Templates Program to Swap Two Numbers Using Function Template

C++ Templates: Program to Swap Two Numbers Using Function Template

What are Templates in C++?
Templates help in defining generic classes and functions and hence allow generic programming. Generic programming is an approach where generic data types are used as parameters and the same piece of code work for various data types.

Function templates are used to create family of functions with different argument types. The format of a function template is shown below:

template<class T>
return_type function_name (arguments of type T)
{
                . . . . .
                . . . . .
}

I have written a program below which will swap two numbers using function templates.

#include<iostream>

using namespace std;

template <class T>
void swap(T&a,T&b)      //Function Template
{
    T temp=a;
    a=b;
    b=temp;
}

int main()
{
    int x1=4,y1=7;
    float x2=4.5,y2=7.5;

    cout<<"Before Swap:";
    cout<<"
x1="<<x1<<" y1="<<y1;
    cout<<"
x2="<<x2<<" y2="<<y2;

    swap(x1,y1);
    swap(x2,y2);

    cout<<"

After Swap:";
    cout<<"
x1="<<x1<<" y1="<<y1;
    cout<<"
x2="<<x2<<" y2="<<y2;

    return 0;
}

There are so many things that I have missed in this tutorial. In below video templates are explained very nicely. I am sure that after watching this video you will understand templates very easily.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.