Two different mixin patterns in C++. (mixin? CRTP?)

前端 未结 2 1326
情深已故
情深已故 2021-01-04 07:21

I\'m studying about mixins (in C++). I read some articles on mixins and found two different patterns of \"approximating\" mixins in C++.

Pattern 1:

t         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-04 07:59

    The difference is visibility. In the first pattern, MyType's members are directly visible to and usable by the mixins, without any need for casting, and Mixin1's members are visible to Mixin2. If MyType wants to access members from the mixins, it needs to cast this, and there isn't a great way to do so safely.

    In the second pattern, there is no automatic visibility between the type and the mixins, but the mixins can safely and easily cast this to MyTypeWithMixins and thereby access the members of the type and of other mixins. (MyType could too, if you applied the CRTP to it too.)

    So it comes down to convenience versus flexibility. If your mixins are purely accessing services from the type, and have no sibling dependencies of their own, the first pattern is nice and straightforward. If a mixin depends on services provided by the type or other mixins, you're more or less forced to use the second pattern.

提交回复
热议问题