C++ 模板 : 'is not derived from type'

标签 c++ templates compilation

为什么这个代码无效?

#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/

相关文章:

c++ - 需要创建中缀到后缀算法

c++ - 如何在 MSVS 开发提示符之外运行 MSBuild?

c++ - 重载赋值运算符 C++

c++ - 枚举变量作为动态模板参数

c++ - map 比较构造函数参数

windows - OpenSSL Windows x64 编译错误

html - CSS 错误编译

c++ - Libgit2 - 无法验证 SSH session : Unable to open public key file

c++ - 在 C++ 中既不调用 Copy 也不调用 Move 构造函数

java - 部署 Java 应用程序。如何?