I have a function, which reads input from a file and appends each line of the file to an STL object. I want to use this function with both lists and vectors. Since both of these objects have the push_back method, I thought I'd make a common function that can be used by both. Is there any practical way to do this?
Function show below:
Function show below:
Code:
template<class container>
// The second argument here must be a list, vector, or any other STL object with a push_back() method
void fileToContainer(const char* fName, container* vecptr) {
// Open a file and add each line to the list, vector, etc.
ifstream f(fName);
string line;
if (f.is_open()) {
while (! f.eof()) {
getline(f, line);
if (line != "") {
try {
vecptr.push_back(line);
}
catch (...) {
throw ios_base::failure("Invalid container object");
}
}
}
}
else {
throw ios_base::failure("Could not open " + static_cast<string>(fName));
}
Comment