Writing and Reading from file Templated List

I have a templated class with a list in it which the user will fill with either ints or doubles. The user will also have the ability to save and load files with list. I think i know how to load it, but not how to save it.

Here is my code which i think will succeed in loading it, took it from a previous project ive made:
1
2
3
4
5
6
7
8
template<typename T>
void ListManipulator<T>::loadFromFile()
{
	std::ifstream inFile(FILENAME);
	std::istream_iterator<T> eos;
	std::istream_iterator<T> iit(inFile);
	std::copy(iit, eos, std::back_inserter(*theList));
}
That might work, but what if you want to load from a different file? What if you want to load from cin, or a stringstream?

Keep this in mind: the purpose of your class methods isn't necessarily to "do the work." The purpose is to "make doing the work easy." If you think like this, you'll write much more general code.

In this case, I'd make the method
1
2
template<typename T>
void ListManipulator<T>::loadFromFile(instream &is)
The user wont have the choice to save different files. I thought the solution would be, if <T>==int, then the file will be saved ass INTLIST.TXT, if double DOUBLELIST.TXT

When loading from file, if template class iss double, than it loads doublelist and vise verca,

But cant get it to work how to write on file.
Why not do this explicitly? Something like:

1
2
3
4
5
6
7
8
9
template<typename T>
void ListManipulator<T>::loadFromFile()
{
	std::ifstream inFile(FILENAME);
	T val;
	while (inFile >> val) {
		theList->push_back(val);
	}
}
Last edited on
Topic archived. No new replies allowed.