Click here to Skip to main content
13,703,250 members
Rate this:
 
Please Sign up or sign in to vote.
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 4 days ago
Updated 4 days ago
Comments
saide_a 4 days ago
   
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

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web01-2016 | 2.8.180920.1 | Last Updated 16 Sep 2018
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100