Friday, March 16, 2012

Templates in C++ !!

                Assume that there is a scenario where you need to find the max of two integers, double and char's. So you will write three different max functions for each. Here the code for all functions are same, the only difference is datatype. To avoid such a duplicate code , C++ supports a feature called Templates. Using templates, we can write a generic function which works for all data types. There are two types of templates namely function templates and class templates.
                The syntax is given below. It starts with template keyword followed by enclosing either class or typename keyword and generic type name in <, > and followed by function defintion. Both syntax's works similarly. There is no difference.

Syntax:
template <class generic_type [class generic_type] [class generic_type]>
function_definition

Function templates: A function template is like a normal function only, except the arguement type. A single function defintion works for different data types. A function will not store in memory. Actual function definition will be generated at the time of compilation basing on the data type.

 
Example:

using namespace std;

template <typename T>
T add(T a,T b)
{
    return (a+b);
}

main()
{
cout<<"2+3 is "<<(add(2,3))<<"\n";
cout<<"2.3+2.3 is "<<(add(2.3,2.3))<<"\n";
//cout<<"2+2.3 is "<<(add(2,2.3))<<"\n"; Illegal , arguments for the add function should be same type.
}

OutPut:
2+3 is 5
2.3+2.3 is 4.6

Class Template: Is a class in which member data are generic data types.See the below sample code .

using namespace std;

template <typename T>
class tmp{
    public:
        T a,b;
        tmp(T x, T y):a(x),b(y)
        {
            cout<<"a n b are "<<a<<" "<<b<<endl;
        }
};

int main()
{
tmp<int> o(2,3);
tmp<double> a1(2.3,3.4);
}

OutPut:
a n b are 2 3
a n b are 2.3 3.4

No comments:

Popular Posts