为什么这个代码无效?
#include <vector>
template <typename T>
class A {
public:
A() { v.clear(); }
std::vector<A<T> *>::const_iterator begin() {
return v.begin();
}
private:
std::vector<A<T> *> v;
};
GCC 报告以下错误:
test.cpp:8: error: type 'std::vector<A<T>*, std::allocator<A<T>*> >' is not derived from type 'A<T>'
test.cpp:8: error: expected ';' before 'begin'
test.cpp:12: error: expected `;' before 'private'
怎么了?如何解决?
最佳答案
在这一行中,您缺少 typename
关键词:
std::vector<A<T> *>::const_iterator begin(){
你需要:
typename std::vector<A<T> *>::const_iterator begin(){
这是因为 std::vector<A<T> *>
取决于类模板 ( T
) 的模板参数 ( A
)。为了能够正确解析模板而不必对任何其他模板的可能特化做出任何假设,语言规则要求您使用 typename
指示哪些依赖名称表示类型关键字。
关于C++ 模板 : 'is not derived from type' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2841757/