为什么我可以通过模板类扩展私有嵌套类?

时间:2011-06-12 23:02:36

标签: c++ templates inheritance nested

我遇到了一些奇怪的问题,模板类似乎可以扩展私有嵌套类。

给出以下私有嵌套类:

class A {
private:
  class B {
  protected:
    void doSomething() {
      ...
    }
  };
};

以下内容未按预期编译:

class C : public A::B {
public:
  C() {
    this->doSomething();
  }
};

但是,gcc似乎很乐意接受以下编译而没有呜咽的实际操作,并且实际上调用了该方法:

template<typename T>
class C : public A::B {
public:
  C() {
    this->doSomething();
  }
};

有没有人知道这是否是使用模板时的预期行为,或者我在gcc中发现了一个奇怪的现象。我在版本4.4.5(Ubuntu / Linaro 4.4.4-14ubuntu5)所以我意识到我有点过时了。如果这是预期的行为,我会非常感谢解释(或指向解释的指针),因为它不是我所期待的,我想知道更多关于它的信息。

非常感谢, 马特

1 个答案:

答案 0 :(得分:7)

那应该是编译器错误。不能从A朋友的任何类访问该类,包括类模板的任何实例化。

GCC 4.2.1和4.6接受该代码

Clang ++拒绝它并显示错误消息

error: 'B' is a private member of 'A'
  struct C : A::B {

Comeau用类似的消息拒绝代码

error: class "A::B" (declared at line 5) is inaccessible
struct C : A::B {
              ^
      detected during instantiation of class "C<T> [with T=int]"