Reputation: 25
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.
Upvotes: 2
Views: 123
Reputation: 362147
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
.)
FileStream<T>&
reference. The &
ensures that you work with the original stream object and not a copy.FileStream<T>&
reference, not an ifstream
.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).
Upvotes: 1