Method chaining + inheritance don't play well together?

后端 未结 15 761
北荒
北荒 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

    For a while there I thought that it might be possible to overload the slightly unusual operator->() for chaining methods instead of ., but that faltered because it seems the compiler requires the identifier to the right of the -> to belong to the static type of the expression on the left. Fair enough.

    Poor Man's Method Chaining

    Stepping back for a moment, the point of method chaining is to avoid typing out long object names repeatedly. I'll suggest the following quick and dirty approach:

    Instead of the "longhand form":

    btn.move(Point(0,0)); btn.setText("Hey");
    

    You can write:

    {Button& _=btn; _.move(Point(0,0)); _.setText("Hey");}
    

    No, it's not as succinct as real chaining with ., but it will save some typing when there are many parameters to set, and it does have the benefit that it requires no code changes to your existing classes. Because you wrap the entire group of method calls in {} to limit the scope of the reference, you can always use the same short identifier (e.g. _ or x) to stand for the particular object name, potentially increasing readability. Finally, the compiler will have no trouble optimising away _.

提交回复
热议问题