声明一个C++ set迭代器

mat*_*ots 1 c++ templates iterator compiler-errors

可能重复:
我必须在何处以及为何要使用"template"和"typename"关键字?
c ++模板typename迭代器

以下代码将无法编译:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误说:

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
Run Code Online (Sandbox Code Playgroud)

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

如果它有用,看起来,如果我用迭代器注释掉这一行,就没有错误.但是,到目前为止我在网上看到的所有例子似乎都是这样宣告迭代器的.我认为.

Ben*_*ley 9

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

typename set<T>::iterator it;
Run Code Online (Sandbox Code Playgroud)

每当引用依赖于模板参数的类型时,都需要执行此操作.在这种情况下,iterator依赖于T.否则,编译器很难弄清楚它是什么iterator,是类型,静态成员还是其他东西.(从技术上讲,它并没有试图弄明白,它已经做出了决定,它恰好是错的)

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

set<int>::iterator it;
Run Code Online (Sandbox Code Playgroud)

typename是没有必要的.