C++: Understanding Template

C++’s class templates provide a better way to generate generic class declarations.Templates provide parameterized types—that is, they are capable of passing a type name as an argument to a recipe for building a class or a function. By feeding the type name int to a Queue template, for example, you can get the compiler to construct a Queue class for queuing ints.

Defining Template:
 template <class Type>


The keyword template informs the compiler that you’re about to define a template. The part in angle brackets is analogous to an argument list to a function. You can think of the keyword class as serving as a type name for a variable that accepts a type as a value, and of Type as representing a name for this variable.

When a template is invoked, Type will be replaced with a specific type value, such as int or string.

It’s important to realize that these templates are not class and member function definitions. Rather, they are instructions to the C++ compiler about how to generate class and member function definitions.

In this program a class Array is made and its one object stores integer type value and other object stores character type value.

#include <iostream>template <class T>
class Array{   int size;   T *array;public:    Array(int s)    {    size=s;    array =new T[size];    }
    void setValue()    {     for(int i=0;i<size;i++)     {      std::cin>>array[i];     }    }    void display()    {    for(int i=0;i<size;i++)    {      std::cout<<array[i]<<" ";    }    }};int main(){   Array<int> arr1(5);   std::cout<<"Enter Numbers\n";   arr1.setValue();   arr1.display();   Array<char> arr2(5);   std::cout<<"\nEnter Characters\n";   arr2.setValue();   arr2.display();    return 0;}


 Follow us on
                              
                                                                  
                                                                  
Reference:
Template

You may also like:

C++: Pointers
C++: Swapping Node LInks in Linked List 
C++: STL Iterators
C++: Program to find smallest element is an array which is repeated exactly 'k' times
C++ STL :Implementation of Counting sort (Sorting)

Comments

Popular Posts

Top 10 Web Sites Every Programmer Should Visit Daily

C++: Huffman Coding using STL

What is "namespace" and why do we use it?