任何人都可以建议为什么这不编译?我想我错过了一些重要的东西.编译器是g ++ 4.2.1(在OS X上),错误是"预期的`;" 在'it'之前,在声明迭代器的行上.
#include <vector>
template <class T>
class A {
public:
struct SomeStruct {
T* ptr;
int i;
};
typedef std::vector<SomeStruct> MyList;
void Func()
{
MyList::iterator it;
}
};
Run Code Online (Sandbox Code Playgroud)
更改:
MyList::iterator it;
Run Code Online (Sandbox Code Playgroud)
至:
typename MyList::iterator it;
Run Code Online (Sandbox Code Playgroud)
我认为这与编译器无法确定是否MyList::iterator应该是某种类型的值(例如,它iterator是静态成员MyList)或类型有关.typename强制后者(正确)选项.
我相信相关的标准报价从这里开始,第二个14.6:
假定模板中使用的名称不是为类型命名,除非适用的名称查找找到类型名称或名称由关键字限定
typename.
所以,你必须弄清楚"适用的名称查找"是什么,但标准也跟着这个例子:
// no B declared here
class X;
template<class T> class Y {
class Z; // forward declaration of member class
void f() {
X* a1; // declare pointer to X
T* a2; // declare pointer to T
Y* a3; // declare pointer to Y<T>
Z* a4; // declare pointer to Z
typedef typename T::A TA;
TA* a5; // declare pointer to T’s A
typename T::A* a6; // declare pointer to T’s A
T::A* a7; // T::A is not a type name:
// multiply T::A by a7
B* a8; // B is not a type name:
// multiply B by a8; ill-formed,
// no visible declaration of B
}
};
Run Code Online (Sandbox Code Playgroud)