简体   繁体   English

在嵌套在C ++模板中的类中使用基类成员时出错

[英]Error when using a member of a base class in a class nested within a template in C++

Consider the following example: 请考虑以下示例:

template <typename T>
struct A {
  struct B {
    int b;
  };

  struct C : B {
    void f() {
      b = 0;
    }
  };
};

Compiling it with GCC 4.8.1 gives the following error: 使用GCC 4.8.1进行编译会出现以下错误:

test.cc: In member function ‘void A<T>::C::f()’:
test.cc:9:11: error: ‘b’ was not declared in this scope
           b = 0;
           ^

However, b is a member of the parent class B (I used struct in the example to make everything public) and if I make A non-template everything compiles. 但是, b是父类B的成员(我在示例中使用了struct来使所有内容都公开),如果我创建A非模板,则所有内容都会编译。

Why is the compiler giving this error and how can I avoid it? 为什么编译器会出现此错误,如何避免错误?

This is kind of an obscure corner case in the language, but the solution is simple, qualify it: 这在语言中是一个模糊的角落案例,但解决方案很简单,符合条件:

this->b = 0; // alternatively 'B::b = 0;'

The reason is that without the qualification b is not a dependent name, and it needs to be resolved in the first pass of lookup, before the actual type is substituted into the template. 原因是没有限定条件b不是依赖名称,并且在将实际类型替换为模板之前需要在查找的第一遍中解析。 At this point the compiler does not know whether there can be an specialization of A<T>::B for the type that will be instantiated, or whether that specialization might have a b member. 此时,编译器不知道是否可以对将要实例化的类型的A<T>::B进行特化,或者该特化是否可能具有b成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM