C++模板:'不是从类型'派生的'

All*_*lan 7 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;
};
Run Code Online (Sandbox Code Playgroud)

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

怎么了?怎么解决?

CB *_*ley 13

在这一行中,您缺少typename关键字:

std::vector<A<T> *>::const_iterator begin(){
Run Code Online (Sandbox Code Playgroud)

你需要:

typename std::vector<A<T> *>::const_iterator begin(){
Run Code Online (Sandbox Code Playgroud)

这是因为std::vector<A<T> *>它取决于T类template(A)的模板parameter ().为了能够正确解析模板而无需对任何其他模板的可能特化进行任何假设,语言规则要求您使用typename关键字指示哪些从属名称表示类型.