gpt4 book ai didi

c++ - C++ 类模板的奇怪错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:24:01 26 4
gpt4 key购买 nike

谁能建议为什么这不能编译?我想我在这里遗漏了一些重要的东西。编译器是 g++ 4.2.1(在 OS X 上),错误是“expected `;'在声明迭代器的行的‘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;
}
};

最佳答案

改变:

MyList::iterator it;

到:

typename MyList::iterator it;

我认为这与编译器不确定 MyList::iterator 是否应该是某种值有关(假设 iterator 是静态的MyList 的成员)或类型。 typename 强制使用后一个(正确的)选项。

我相信相关的标准引用从这里开始,第二个 14.6:

A name used in a template is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword 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
}
};

关于c++ - C++ 类模板的奇怪错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4024773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com