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
{
size = max;
data = new T[size];
}//end constructor
template < class T >
T& Array
{
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
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
{
size = max; data = new T[size];
}//end constructor
Regards,
sahu
No comments:
Post a Comment