2

My teacher wanted us to learn the ifstream class and how it works. She gave us homework to create a FileStream wrapper class that is templated to work with anything and can take in anything that's in the file.

I have written everything except I can't get it to compile because I don't know how to write the >> operator and keep getting errors for it. This is what I have so far:

template<class A>
ifstream& operator >>(FileStream<A> fs, A& x){
  fs>>x;
  return fs;
}

In the main she is using to check our work it is called like this:

FileStream<Word> input;
Word temp; //word is a class we created to manipulate strings in certain ways 

while(input>> temp){
  cout<<temp<<endl;
}

If anyone could help me out I would be most grateful. I've been working on this for 2 days and I can't get it.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
user1828256
  • 25
  • 1
  • 3

1 Answers1

1
template<class T>
FileStream<T>& operator >> (FileStream<T>& fs, T& value) {
  value = fs.readValueFromStream();
  return fs;
}

Your method should look something like the above. Highlights:

(Note that I've renamed A to T and x to value. T is the usual name for generic template arguments, and value is a bit more descriptive than x.)

  1. Accepts a FileStream<T>& reference. The & ensures that you work with the original stream object and not a copy.
  2. Returns a FileStream<T>& reference, not an ifstream.
  3. Rather than doing fs>>x in the method, which would just be a recursive call to the very method we're in, you need to write code to actually read an item from the stream and put it into value. This should use some method of your FileStream class. I wrote value = fs.readValueFromStream() but this could be anything.

In this way operator >> serves as syntactic sugar. The real work is done by the value = fs.readValueFromStream() line (or whatever code you actually write there).

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • but then what is that readItemFromStream() method? Do you re-open the file and read from it as a normal ifstream? – user1828256 Nov 16 '12 at 01:04
  • @user1828256 Good question. Perhaps you could post it as a separate follow-up question, linking back to this one. I don't think I'll be able to answer it properly tonight. – John Kugelman Nov 16 '12 at 01:37
  • i actually just made an array in my constructor loaded everything into that and now my >> operator read from that array and delete the first object in it untill no more – user1828256 Nov 16 '12 at 02:08