Wednesday, September 12, 2007

What is template instantiation

A C++ template is a framework for defining a set of classes or functions.
The instantiation, creates a particular class or function , by resolving the C++ template with a group of arguments that may be types or values.

Lets have an example.

#include < iostream >
#include < new >
#include < stdexcept >

using namespace std;
template < class T >
class Array
{

T *data; // pointer to heap allocated space
int size; // maximum size
public: T &operator[](int);
Array(int max);

};

template < class T >
Array::Array(int max)
{
size = max;
data = new T[size];

}//end constructor

template < class T >
T& Array::operator[](int index)
{
if (index < 0 || index > = size)
{
throw out_of_range("Array");
}
return data[index];
}//end Array

int main()
{
Array< double > test1(100);
test1[25] = 3.14;
cout< < test2(200);
Array < int > test2(200);
test2[0] = 55;
return 1;

}//end main

Now we will discuss what is instantiation ?
Here ,Array instantiates Array with type int.
This instantiation generates the following class definition:
class Array
{
int *data;
int size;
public:
int &operator[](int);
};

Like that it instatiate for float etc.
So now, we have understood what is instantiation.

Q 2) How to write the methos definition out side the class if it is a template class?

fist write the template type that the class use. Here in our case
template
then in as usual manner like reurn type then class name then method name with signature
Array::Array(int max)
{
size = max; data = new T[size];

}//end constructor



Regards,

sahu

No comments: