Method chaining + inheritance don't play well together?

后端 未结 15 799
北荒
北荒 2020-12-08 22:20

Consider:

// member data omitted for brevity

// assume that \"setAngle\" needs to be implemented separately
// in Label and Image, and that Button does need         


        
15条回答
  •  悲&欢浪女
    2020-12-08 23:06

    I think (I haven't tested it) this will do it using templates:

    template struct TWidget {
        T& move(Point newPos) { pos = newPos; return (T&)*this; }
    };
    
    template struct TLabel : TWidget { ... }
    
    struct Label : TLabel

    Notes:

    • Any/every base class needs to be a template, with a separate non-template leaf class at the top (contrast the LabelT and Label classes).
    • The cast could be a dynamic_cast if you like.
    • Instead of casting the "return *this", the base class could contain a T& as a data member (the derived class would pass this to the base class' constructor), which would be an extra data member, but which avoids a cast and I think may permit composition instead of or as well as inheritance.

提交回复
热议问题