【问题标题】:"typename vector<T>::iterator" does not recognized by compiler编译器无法识别“typename vector<T>::iterator”
【发布时间】: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&lt;typename It&gt; void f(It it); 这样的函数(然后仍然使用f(v.begin()))。如果确实需要容器类型,则必须传递另一个参数 (template&lt;class Cont, class It&gt; void f(Cont&amp;, It);) 或显式指定模板参数 template&lt;class Cont, class It&gt; void f(It); f&lt;std::vector&lt;int&gt;&gt;(v.begin());)。

标签: c++ templates typename


【解决方案1】:

你的函数需要一个迭代器,但你试图传递一个向量。您可能指的是f(v.begin()) 或类似的东西。

另外,正如@chris 所说,T 处于不可演绎的上下文中。必须明确提供,如f&lt;int&gt;(v.begin());

【讨论】:

  • sry,这是一个错误的输入。问题中是 f(v.begin())
【解决方案2】:

问题在于模板参数推导适用于大约 20 种不同的形式,但不适用于 typename Foo&lt;T&gt;::Bar 形式。原因是Foos 有无限多个,并且每个Bar 都可以有一个与您匹配的嵌套类型Bar。编译器无法搜索所有这些。

std::vector&lt;T&gt;::const_iteratorstd::vector&lt;const T&gt;::const_iterator 是此类问题的一个很好的例子,它们很可能是同一类型。

因此,它被称为非推断上下文。你必须明确你想要哪个模板。

【讨论】:

  • 这实际上并没有回答问题(即“如何解决?”)
【解决方案3】:

修复编译器错误的一种方法是明确模板参数。

f<int>(v.begin());

【讨论】:

    【解决方案4】:

    您将v(即vector&lt;int&gt;)传递给函数f。您应该将迭代器传递给f

    只需将模板函数重新设计为

    template<typename Iterator>
    void f(Iterator it)
    { 
       // manipulate iterator it
    }
    

    那你可以打电话

    vector<int> v;
    
    f(v.begin());
    

    【讨论】:

    • 我很抱歉,这是我的问题中的一个错误类型。实际上它确实是 f(v.begin()) 但不起作用。
    猜你喜欢
    • 1970-01-01
    • 2013-07-29
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    相关资源
    最近更新 更多