How to implement an interface class using the non-virtual interface idiom in C++?

前端 未结 4 1656
猫巷女王i
猫巷女王i 2020-12-19 15:10

In C++ an interface can be implemented by a class whose methods are pure virtual.

Such a class could be part of a library to describe what methods an object should

4条回答
  •  自闭症患者
    2020-12-19 16:07

    You could use the pimpl-idiom to achieve this:

    class IFoo
    {
        public:
            IFoo( boost::shared_ptr< IFooImpl > pImpl )
                : m_pImpl( pImpl )
            {}
    
            void method() { m_pImpl->method(); }
            void otherMethod() { m_pImpl->otherMethod(); }
        private:
            boost::shared_ptr< IFooImpl > m_pImpl;
    };
    
    class IFooImpl
    {
        public:
            void method();
            virtual void otherMethod();
    };
    

    Now others can still subclass IFooImpl and pass it to IFoo, but they cannot override the behavior of method (they can override otherMethod). You can even make IFooImpl a direct subclass of IFoo and use enable_shared_from_this to initialize IFoo correctly. This is just the gist of the method. There are many ways to tweak this approach. For instance you can use the factory-pattern to make sure IFoos are created correctly.

    Hope that helps.

提交回复
热议问题