I am implementing a template function to read a file and file-like entities into a vector line by line:
#include <iostream>
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <fstream>
using namespace std;
template<typename T> vector<T> readfile(T ref1)
{
std::vector<T> vec;
std::istream_iterator<T> is_i;
std::ifstream file(ref1);
std::copy(is_i(file), is_i(), std::back_inserter(vec));
return vec;
}
I look to read a file using the following code in main:
int main()
{
std::string t{"example.txt"};
std::vector<std::string> a = readfile(t);
return 0;
}
I get the error:
“no match for call to ‘(std::istream_iterator, char, …
Let me know if I need to supply more of the error message. Chances are I am just messing up something simple. But I can’t understand why – using tutorials I have gotten this and I thought it to be a pretty good solution.
You apparently meant to turn
is_iinto a type but instead declared a variable of typestd_istream_iterator<T>. You probably meant to write:You should probably also decouple your template argument from the type used for the file name as the template is otherwise fairly restrictive: