As an assignment at the beginning of my class I had to create a class to read in integer form a file and print them back out in another(combination review of file IO and classes). Now I am supposed to take that class and make it a template class so that it will work with any data type. I did that, and it tests fine with ints, but when I throw it another class I used it goes crazy....Here's the read function and the overloaded extraction operator for the other class. NOTE: array is declared to be of type TYPE.
template<class TYPE>
bool Reader<TYPE>::read_array()
{
//Also, since the first number could be wrong, I am going to just ignore it
//This function will return false if there are more than 50 entries in the file.
int temppos(0);
inFile >> readSize;
while ((inFile >> array[temppos]) && temppos <= SIZE) //Do while there are items to read and we have not exceeded 50
{
temppos++; ///Make sure to increase the position
}
if (!inFile.eof()) //There are still numbers in the file
{
cerr << "There were too many entries in the file\n";
returnfalse;
}
if (readSize != temppos) //If the size indicated was false
{
cout << "Warning: There were a different number of entries in the file than information from the file indicated!!!\n"
<< "Don't Panic! It's OK." << endl; //It's amusing to me
readSize = temppos; //Set the value correct
}
returntrue;
}
Your read_array doesn't really stand alone. It uses a global in array called array that is SIZE big.
These types don't change when TYPE is changed from int to string for example. Doing so causes read_array() to attempt to read a string into the int array.
So clearly, the function must take the array as a parameter that is dependent on TYPE.