Fluent interfaces and inheritance in C++

前端 未结 5 2044
失恋的感觉
失恋的感觉 2020-12-16 21:11

I\'d like to build a base (abstract) class (let\'s call it type::base) with some common funcionality and a fluent interface, the problem I\'m facing is the retu

5条回答
  •  悲哀的现实
    2020-12-16 21:46

    You should be returning references/pointers, and you should not need to keep the type information.

    class base {
      public:
         base();
         virtual ~base();
    
         base &with_foo();
         base &with_bar();
      protected:
         // whatever...
    };
    
    class my_type : public base {
      public:
        my_type();        
        // more methods...
    };
    
    base *build_my_type()
    {
       return &new my_type()->with_foo().with_bar();
    }
    

    You already have a virtual destructor. Presumably you have other virtual functions. Access everything through the base type and the virtual functions declared there.

提交回复
热议问题