【发布时间】:2013-10-25 10:19:46
【问题描述】:
现在我有一个这样的模板方法:
template<typename T>
void f(typename vector<T>::iterator it)
{
//implemenation
...
}
int main()
{
vector<int> v;
//initialization of v;
...
f(v.begin());
return 0;
}
但是当我编译为“g++ THIS_FILE -o TARGET_RUNNABLE”时,编译显示
no matching function for call to ‘f(std::vector<int>::iterator)’
template argument deduction/substitution failed:
couldn't deduce template parameter ‘T’
我确实意识到在 vector::iterator 之前添加关键字 "typename"。但这仍然是错误的。有人知道如何解决这个问题吗?
【问题讨论】:
-
你不能这样推断。
-
你不能从一个迭代器类型中可移植地推断出容器类型。通常,人们会编写像
template<typename It> void f(It it);这样的函数(然后仍然使用f(v.begin()))。如果确实需要容器类型,则必须传递另一个参数 (template<class Cont, class It> void f(Cont&, It);) 或显式指定模板参数template<class Cont, class It> void f(It); f<std::vector<int>>(v.begin());)。