[英]“typename vector<T>::iterator” does not recognized by compiler
现在,我有一个这样的模板方法:
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” 。 但这仍然是错误的。 有人知道如何解决此问题吗?
您的函数需要一个迭代器,但是您正在尝试传递向量。 您可能已经说过f(v.begin())
或类似的东西。
而且,正如@chris所指出的, T
在不可推论的上下文中。 必须像f<int>(v.begin());
一样明确提供它f<int>(v.begin());
您将v
为vector<int>
到函数f
。 您应该将迭代器传递给f
。
只需重新设计模板功能即可
template<typename Iterator>
void f(Iterator it)
{
// manipulate iterator it
}
那你可以打电话
vector<int> v;
f(v.begin());
问题在于,模板参数推导适用于大约20种不同的形式,但不适用于typename Foo<T>::Bar
。 原因是有无限多个Foo
,并且每个Foo
都可以有一个与您的嵌套类型相匹配的嵌套Bar
。 编译器无法搜索所有它们。
此类问题的一个很好的例子是std::vector<T>::const_iterator
与std::vector<const T>::const_iterator
,这可能是相同的类型。
因此,它被称为非推论上下文 。 您必须明确要使用哪个模板。
解决编译器错误的一种方法是明确指定template参数。
f<int>(v.begin());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.