【问题标题】:declaring a C++ set iterator [duplicate]声明一个 C++ 集合迭代器 [重复]
【发布时间】:2012-07-03 12:08:37
【问题描述】:

可能重复:
Where and why do I have to put the “template” and “typename” keywords?
c++ template typename iterator

以下代码将无法编译:

#include <iostream>
#include <set>
using namespace std;

template<class T>
void printSet(set<T> s){
    set<T>::iterator it;
}

int main(int argc, char** argv){
    set<int> s;
    printSet<int>(s);
    return 0;
}

我收到一条错误消息:

set.cpp: In function ‘void printSet(std::set<T, std::less<_Key>, std::allocator<_CharT> >)’:
set.cpp:7: error: expected `;' before ‘it’
set.cpp: In function ‘void printSet(std::set<T, std::less<_Key>, std::allocator<_CharT> >) [with T = int]’:
set.cpp:12:   instantiated from here
set.cpp:7: error: dependent-name ‘std::set<T,std::less<_Key>,std::allocator<_CharT> >::iterator’ is parsed as a non-type, but instantiation yields a type
set.cpp:7: note: say ‘typename std::set<T,std::less<_Key>,std::allocator<_CharT> >::iterator’ if a type is meant

我做错了什么?我觉得我几乎没有写过任何东西,而 C++ 已经给了我这个可怕的信息。

如果它有帮助,看起来,如果我用迭代器注释掉该行,就没有错误。但是,到目前为止,我在网上看到的所有示例似乎都以这种方式声明迭代器。我想。

【问题讨论】:

  • 仔细阅读错误信息的最后两行。

标签: c++ templates compiler-errors iterator


【解决方案1】:

在您的声明前加上关键字typename,因此:

typename set<T>::iterator it;

每当您引用依赖于模板参数的类型时,您都需要这样做。在这种情况下,iterator 依赖于 T。否则,编译器很难弄清楚 iterator 是什么,它是一个类型,还是一个静态成员或其他什么。 (嗯,从技术上讲,它并没有试图弄清楚,它的决定已经做出,只是碰巧是错误的)

请注意,如果您有具体类型,例如:

set<int>::iterator it;

typename 不是必需的。

【讨论】:

  • 嗯...为什么需要 typename?
  • 谢谢!有用!但这似乎有点像黑魔法。我什么时候知道我需要输入typename
  • @math4tots:添加了解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-22
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
相关资源
最近更新 更多