Method chaining + inheritance don't play well together?

后端 未结 15 747
北荒
北荒 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条回答
  •  -上瘾入骨i
    2020-12-08 23:08

    This compiles on gcc 4.3.2 and is sort of a mixin pattern.

    #include 
    
    using namespace std;
    
    struct Point {
        Point() : x(0), y(0) {}
        Point(int x, int y) : x(x), y(y) {}
    
        int x, y;
    };
    
    template 
    struct Widget {
        T& move(Point newPos) {
            pos = newPos;
            return *reinterpret_cast (this);
        }
    
        Point pos;
    };
    
    template 
    struct Label : Widget > {
        T& setText(string const& newText) {
            text = newText;
            return *reinterpret_cast (this);
        }
        T& setAngle(double newAngle) {
            angle = newAngle;
            return *reinterpret_cast (this);
        }
    
        string text;
        double angle;
    };
    
    struct Button : Label

提交回复
热议问题