使用ifstream我的模板功能有什么问题?

Pin*_*ade 0 c++ templates vector

我正在实现一个模板函数来逐行将文件和类文件实体读入一个向量:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我希望在main中使用以下代码读取文件:

int main()
{
    std::string t{"example.txt"};
    std::vector<std::string> a = readfile(t);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我得到错误:"无法匹配'(std :: istream_iterator,char,...

如果我需要提供更多错误消息,请告诉我.机会是我只是弄乱了一些简单的东西.但我无法理解为什么 - 使用教程我得到了这个,我认为这是一个非常好的解决方案.

Die*_*ühl 5

你显然打算is_i变成一个类型,而是声明一个类型的变量std_istream_iterator<T>.你可能想写:

typedef std::istream_iterator<T> is_i;
Run Code Online (Sandbox Code Playgroud)

您可能还应该将模板参数与用于文件名的类型分离,因为模板具有相当大的限制性:

template <typename T>
std::vector<T> readfile(std::string const& name) {
    ...
}

std::vector<int> values = readfile<int>("int-values");
Run Code Online (Sandbox Code Playgroud)