What are Templates in C++ ? How are Templates declared and used ?

October 28, 2007 · Filed Under C++ Questions, Placement Questions 



Don't want to miss a single bit? Subscribe By Email for Daily Jobs

Enter your email address :

All the latest from JobsAdda on Jobsadda.com delivered to your mailbox everyday.

Many data structures and algorithms can be defined independently of the type of data they manipulate.

A template allows the separation of the type dependent part from the type independent part. This results in a significant amount of code reusability. Templates can be class templates or function templates. A class template is used for creating a class in which one more values are parameterized. The syntax of a class template is:

template class class-name
{

};

A class template can also have multiple parameters.

template class class-name
{

};

Example -

template class Array
{
private:
T *arr [];
public:
Array (int size = 10);
};
template Array::Array(int size)
{
arr = new T[size];
}

Create an Array object as: Array a; The function template is also written using the keyword template.

E.g. template class void push (T &element)
{
arr[top] = element;
}

Related Articles


Get Latest JobsAdda.com Jobs, news & updates  via Email