Can I cast a derived class to a private base class, using C-style cast?

前端 未结 3 590
说谎
说谎 2020-11-29 11:00

Can I do this?

class A { ... };

class B : private A
{
    const A &foo() const
    {
        return *((const A *)this);
    }
};

Can I

3条回答
  •  迷失自我
    2020-11-29 11:51

    Yes, that is explicitly allowed. Alexandrescu uses this extensively in Modern C++ Design for his approach of policy based design:

    template 
    class foo : Policy
    {
        public:
            void do_something()
            {
                Policy & p = *this;
                p.do_something();
            }
    };
    

    So while the use cases may be limited, there are some out there.

提交回复
热议问题