Click here to Skip to main content
15,899,474 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
// A generic safe array example.
#include <iostream>
#include <cstdlib>
using namespace std;
const int SIZE = 10;
template <class AType> class atype {
AType a[SIZE];
public:
atype() {
register int i;
for(i=0; i<SIZE; i++) a[i] = i;
}
AType &operator[](int i);
};
// Provide range checking for atype.
template <class AType> AType &atype<atype>::operator[](int i)
{
if(i<0 || i> SIZE-1) {
cout << "\nIndex value of ";
cout << i << " is out-of-bounds.\n";
exit(1);
}
return a[i];
}
int main()
{
atype<int> intob; // integer array
atype<double> doubleob; // double array
int i;
cout << "Integer array: ";
for(i=0; i<SIZE; i++) intob[i] = i;
for(i=0; i<SIZE; i++) cout << intob[i] << " ";
cout << '\n';
cout << "Double array: ";
for(i=0; i<SIZE; i++) doubleob[i] = (double) i/3;
for(i=0; i<SIZE; i++) cout << doubleob[i] << " ";
cout << '\n';
intob[12] = 100; // generates runtime error
return 0;
}

What I have tried:

I have searched for it in the web.
Posted
Updated 15-Sep-18 19:58pm
Comments
saide_a 16-Sep-18 0:25am    
Your problem isn't clear for me,
there is a fix size array (10) and in some steps of program values assign to that

1 solution

It's Generics: you declare the generic class atype as accepting a Type for each instance when that instance is created, and it produces an instance which is specific to that type.

So when your code says:
atype<int> intob;
the int tells the atype class to create an array of integers.
While:
atype<double> doubleob;
does teh same but with double values.

This isn't something it;'s easy to explain in a little text box, so if you don't understand then it's time to start reading: Templates - C++ Tutorials[^] and An Idiot's Guide to C++ Templates - Part 1[^] are good starting points.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900