2014-04-10 41 views
0

我想从文件中读取一个载体,但我可能有不同的数据类型那里,我使用模板使用模板来读取矢量

template <class T> 
vector<T> readd(int n) 
{ 
    vector<T> V; 
    for(int i=0;i<n;i++) 
    { 
     T k; 
     fin>>k; 
     V.push_back(k); 
    } 
    return V; 
} 

int main() 
{ 
    vector<int> V; 
    int n; 
    fin>>n; 
    V = readd(n); 
} 

但我有编译错误

error: no matching function for call to readd(int&)

有人可以帮助我...

+0

删除'class U'? – Paranaix

+0

我需要return语句。 – user3260563

+0

您实际上会返回一个'std :: vector ',那么为什么还需要第二个teplate参数?直接写'std :: vector readd(vector V)'或写'自动读取(vector V) - > decltype(V)' – Paranaix

回答

0

您正试图返回V这是什么,但vector<T>

这样做:

template <class T> 
vector<T> readd(int n) 
{ 
    vector<T> V; 
    for(int i=0;i<n;i++) 
    { 
     T k; 
     fin>>k; 
     V.push_back(k); 
    } 
    return V; 
} 

int main() 
{ 
    vector<int> V; 
    int n; 
    fin>>n; 
    //you need to tell the compiler the actual type of T since it is not auto deducible! 
    V = readd<int>(n); 
} 
+0

问题是如果我不通过向量作为参数它不起作用。 对不起,我刚刚忘记在这里复制 – user3260563

+0

你是什么意思,它不工作?无论如何,我不是要求你删除参数,我只是建议将'V'作为参考! – CinCout

+0

新版本: 'vector readd(int n)' and error 'error:没有匹配的函数调用'readd(int&)'' – user3260563

3

您要使用的模板参数推导,但为了这一目标的工作编译器需要能够推断出的类型,你传递给参数的每个模板参数功能。 U没有出现在你的参数列表中,所以编译器不能推断它的类型。

也就是说,自从您立即清除它之后,将值传递给此函数没有任何意义。写你的函数的正规途径是

template <class T> 
std::vector<T> readd(int n) 
{ 
    std::vector<T> v; 
    v.reserve(k); // prevent unnecessary reallocation 
    for (int i = 0; i < n; ++i) 
    { 
     T k; 
     fin >> k; 
     v.push_back(k); 
    } 
    return v; 
} 

,然后调用它像

std::vector<int> v = readd<int>(10); 

你需要指定模板参数,因为它不能被编译器推断。另外,如果fin是一个全局变量,最好将其设置为非全局变量,并将其传递给读取函数。