C ++ Template:'不是从类型' [英] C++ Template: 'is not derived from type'

查看:118
本文介绍了C ++ Template:'不是从类型'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此代码无效?

#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报告以下错误:

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?

推荐答案

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

In this line, you are missing the typename keyword:

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

您需要:

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

这是因为 std ::向量< A< *> 取决于类模板的模板参数( T )( A )。为了能够正确解析模板,而不必对任何其他模板可能的特殊化做出任何假设,语言规则要求您使用 typename 来指示哪些依赖名称表示类型,关键字。

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.

这篇关于C ++ Template:'不是从类型'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆