使用模板访问C ++中的超类的受保护成员 [英] accessing protected members of superclass in C++ with templates

查看:167
本文介绍了使用模板访问C ++中的超类的受保护成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么C ++编译器不能识别 g() b $ c>如下代码中所示的超类:

Why can't a C++ compiler recognize that g() and b are inherited members of Superclass as seen in this code:

template<typename T> struct Superclass {
 protected:
  int b;
  void g() {}
};

template<typename T> struct Subclass : public Superclass<T> {
  void f() {
    g(); // compiler error: uncategorized
    b = 3; // compiler error: unrecognized
  }
};

如果我简化子类 子类< int> 然后它编译。当完全限定 g()超类 :: g()超类< T> :: b 。我使用LLVM GCC 4.2。

If I simplify Subclass and just inherit from Subclass<int> then it compiles. It also compiles when fully qualifying g() as Superclass<T>::g() and Superclass<T>::b. I'm using LLVM GCC 4.2.

注意:如果我使 g()

Note: If I make g() and b public in the superclass it still fails with same error.

推荐答案

这可以通过修改使用使用将名称拉入当前范围:

This can be amended by pulling the names into the current scope using using:

template<typename T> struct Subclass : public Superclass<T> {
  using Superclass<T>::b;
  using Superclass<T>::g;

  void f() {
    g();
    b = 3;
  }
};

或通过 this 指针访问:

template<typename T> struct Subclass : public Superclass<T> {
  void f() {
    this->g();
    this->b = 3;
  }
};

或者,您已经注意到,通过限定全名。

Or, as you’ve already noticed, by qualifying the full name.

这是必要的原因是C ++不考虑名称解析的超类模板(因为它们是依赖名称,不考虑依赖名称)。当您使用超类时,因为它不是模板(它是模板的一个实例化),因此它的嵌套名称不是依赖名称。

The reason why this is necessary is that C++ doesn’t consider superclass templates for name resolution (because then they are dependent names and dependent names are not considered). It works when you use Superclass<int> because that’s not a template (it’s an instantiation of a template) and thus its nested names are not dependent names.

这篇关于使用模板访问C ++中的超类的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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