C++ Template: 'is not derived from type'

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

Why is this code not valid?

#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 reports the following errors:

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' 

What is wrong? How to fix it?

回答1:

In this line, you are missing the typename keyword:

std::vector<A<T> *>::const_iterator begin(){ 

You need:

typename std::vector<A<T> *>::const_iterator begin(){ 

This because std::vector<A<T> *> is dependent on the template parameter (T) of the class template (A). To enable correct parsing of the template without having to make any assumptions about possible specializations of any other templates, the language rules require you to indicate which dependent names denote types by using the typename keyword.



回答2:

You need to add typename as the types depend on each other and the compiler can't figure out if it really is a type.

However, on gcc 4.5.0 i get a more concise error message:

test.cc:8:3: error: need ‘typename’ before ‘std::vector<A<T>*>::const_iterator’ because ‘std::vector<A<T>*>’ is a dependent scope



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!