C++ private inheritance and static members/types

后端 未结 2 1875
情书的邮戳
情书的邮戳 2021-01-12 10:35

I am trying to stop a class from being able to convert its \'this\' pointer into a pointer of one of its interfaces. I do this by using private inheritance via a middle prox

2条回答
  •  悲&欢浪女
    2021-01-12 11:06

    You should be able to access Base::Enum by fully qualifying it:

    class Child : public Middle
    {
    public:
        void Method()
        {
            ::Base::Enum e = ::Base::value;
        }
    };
    

    This is the behavior specified by the language (C++03 §11.2/3):

    Note: A member of a private base class might be inaccessible as an inherited member name, but accessible directly.

    This is followed by an extended example that is effectively similar to your example code.

    However, it appears that neither Visual C++ 2008 nor Visual C++ 2010 correctly implements this, so while you can use the type ::Base::Enum, you still can't access ::Base::value. (Actually, Visual C++ seems to have gotten a lot of this wrong, as it incorrectly allows you to use the not-fully-qualified Base::Enum).

    To "get around" the problem, you can add using declarations to the Middle class:

    class Middle : private Base
    { 
    protected:
    
        using Base::Enum;
        using Base::value;
    };
    

    This won't let you use Base::Enum or Base::value in your Child class, but it will allow you to use an Enum and value or Middle::Enum and Middle::value.

提交回复
热议问题