Pages

Tuesday, December 13, 2016

Generics in C++

C++ provides templates to define short, simple code and avoid code duplication.With templates programmers can define a family of functions or classes that can perform operations on multiple types of data. Through templates, C++ provides generic programming.

Entities such as functions or classes created using generic programming are called generics.

Uses of templates:

1. Templates are widely used to implement the Standard Template Library (STL).
2. Templates are used to create Abstract Data Types (ADTs) and classify algorithms and data                    structures.
3. Class templates are generally used to implement containers.

Function Templates

A function template enables a programmer to write generic code without specifying specific type of data. Template keyword tells the compiler that what follows is a template. Here class is keyword and T is generic argument. You can also use 'typename' instead of 'class'

template<class T> return-type function-name(T a,...){
     //body of template
}

Consider the c++ code below:

#include <iostream>
using namespace std;

//template definition
template<class T> void sum(T x, T y)
{
    cout << "Sum is:" << (x+y) ;
}

int main()
{
int a = 10, b = 20;
sum(a, b);
float p = 1.5, q = 2.4;
sum(p, q);
return 0;
}

Output for the above program is as follows:
Sum is: 30
Sum is: 3.9


Here, in first call to sum, integers are passed and float on the second call to sum.


Class object can also be passed as an argument as follows:

#include <iostream>
using namespace std;

class Student
{
    public:
        int age;
        string name;
 
    Student(int age, string name)
    {
        this->age = age;
        this->name = name;
    }
};

template<class T>void display(T &obj)
{
    cout << "Name is: " << obj.name << endl;
    cout << "Age is: " << obj.age << endl;
}

int main()
{
    Student s(25, "hey");
    display(s);  // object s of class Student passed as an argument.
    return 0;
}

Output for the above program is as follows:
Name is: hey
Age is: 25

No comments:

Post a Comment