简体   繁体   中英

Use protected static function of the base class from the friend of the derived class

Different compiler seems to have different opinion on the subject. The following code compiles fine with gcc , but fails with clang :

class Base {
protected:
    static void f() {}
};

class Derived : public Base {
    friend class DerivedFriend;
};

class DerivedFriend {
public:
    void g() {
        Base::f();
    }
};

clang 's error is:

main.cpp:13:15: error: 'f' is a protected member of 'Base'
        Base::f();
              ^
main.cpp:3:17: note: declared protected here
    static void f() {}
                ^
1 error generated.

This is CWG issue 1873 , which changed the rules for this case ([class.access.base]/p5):

A member m is accessible at the point R when named in class N if

  • [...]
  • m as a member of N is protected, and R occurs in a member or friend of class N , or in a member or friend of a class P derived from N , where m as a member of P is public, private, or protected, or
  • [...]

Here, N is Base , P is Derived , m is f() , and R occurs in a member of DerivedFriend ; pre-CWG1873 this would be allowed, but CWG1873 removed the "friend of a derived class" case and makes this ill-formed.

The fix is to refer to f as a member of Derived rather than Base .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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