c++ - 当你是 friend 时,为什么 GCC 不允许从私有(private)嵌套类继承?

标签 c++ templates inheritance nested friend

问同样的问题:为什么 GCC 允许从私有(private)嵌套类继承? 对于非模板类,它允许从私有(private)嵌套类继承, 如果它是一个 friend ,但不是模板类。 是错误吗?

template<class Base>
class InheritFromBaseMember : public Base::MemberPrivate // error
{
    using PrivateMember = typename Base::MemberPrivate; // works fine
};

class MyBase{
    friend class InheritFromBaseMember<MyBase>;

    // another try to declare it friend
    template<class T>
    friend class InheritFromBaseMember;

    friend class AnotherClass;

    class MemberPrivate{};
};

class AnotherClass : public MyBase::MemberPrivate{}; // works fine

int main() {
    InheritFromBaseMember<MyBase>{};
}

来自 g++ 5.3.0 的错误消息:

error: 'class MyBase::MemberPrivate' is private
     class MemberPrivate{};
           ^
error: within this context
 class InheritFromBaseMember : public Base::MemberPrivate // error
       ^

最佳答案

这绝对是一个 gcc 错误。 gcc 有 lots of issues与友元和模板。这个例子几乎完全出现在标准中,在 [class.friend] 下,强调我的:

Declaring a class to be a friend implies that the names of private and protected members from the class granting friendship can be accessed in the base-specifiers and member declarations of the befriended class.
[ Example:

class A {
class B { };
    friend class X;
};

struct X : A::B { // OK: A::B accessible to friend
    A::B mx;      // OK: A::B accessible to member of friend
    class Y {
        A::B my;  // OK: A::B accessible to nested member of friend
    };
};

—end example ]

关于c++ - 当你是 friend 时,为什么 GCC 不允许从私有(private)嵌套类继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37487609/

相关文章:

c# - 显示不同对象的数组c#(类继承)

c++ - `inline` 和 `noexcept` 在 consteval 上下文中是多余的吗?

c++ - Mac OS X 免费 C 编译器

c++ - 如何在 pre-C++11、C++11、14 和 17 中简化复杂的 SFINAE 语法?

c++ - ios项目的预链接静态库

c# - PLY 文件行的更通用的 TryParse()

javascript - 如何创建与其他对象类型相同的新对象

C++ 条件语句

python - 使用来自 C++、PyObject 的参数创建 Python 构造函数

c++ - 在通用编程/TMP 世界中,模型/策略和 "concept"究竟是什么?