C++核心准则C.136:使用多重继承表现“实现属性”的组合

共 1866字,需浏览 4分钟

 ·

2020-02-10 23:25

561656a0de120c984f06af060de97ad7.webp

507bed8e2ca061829995e34f6162ad56.webp

C.136: Use multiple inheritance to represent the union of implementation attributes

C.136:使用多重继承表现“实现属性”的组合。‍



b9271ad71f10927001b7e26d4783bbd9.webp

Reason(原因)

828291b578f55d652668a4614b87c1f6.webp

Some forms of mixins have state and often operations on that state. If the operations are virtual the use of inheritance is necessary, if not using inheritance can avoid boilerplate and forwarding.

某些形式的混入通常包含状态和针对状态的操作。如果操作是虚的,使用继承就是必要的,如果不使用继承可以避免样板和转交。


mixins就是定义一部分公共的方法或属性,然后混入到各个组件中使用,这样可以方便管理与修改



b9271ad71f10927001b7e26d4783bbd9.webp

Example(示例)

828291b578f55d652668a4614b87c1f6.webp
class iostream : public istream, public ostream {   // very simplified
    // ...
};

istream provides the interface to input operations (and some data); ostream provides the interface to output operations (and some data). iostream provides the union of the istream and ostream interfaces and the synchronization needed to allow both on a single stream.

istream提供输入操作的接口(和一些数据);ostream提供了输出操作的接口(和一些数据)。iostream提供istream和ostream接口的组合,同时每个单独的流上都需要允许同步。


b9271ad71f10927001b7e26d4783bbd9.webp

Note(注意)

828291b578f55d652668a4614b87c1f6.webp

his a relatively rare use because implementation can often be organized into a single-rooted hierarchy.

这是一种相对稀少的用法,因为实现通常可以组织成一个单根继承中。


b9271ad71f10927001b7e26d4783bbd9.webp

Example(示例)

828291b578f55d652668a4614b87c1f6.webp

Sometimes, an "implementation attribute" is more like a "mixin" that determine the behavior of an implementation and inject members to enable the implementation of the policies it requires. For example, see std::enable_shared_from_this or various bases from boost.intrusive (e.g. list_base_hook or intrusive_ref_counter).

有时,一个“实现属性"更像一个"minxin",这个"minxin”可以决定一个实现的行为,也可以是使能实现它要求的原则的注入成员。例如,参考std::enable_shared_from_this或者来自boost.intrusive的很多基础类(例如list_base_hook或者instrusive_ref_counter)。


Boost.Instrusive(

https://theboostcpplibraries.com/boost.intrusive

)特别适合高性能编程的C++库。



b9271ad71f10927001b7e26d4783bbd9.webp

Enforcement(实施建议)

828291b578f55d652668a4614b87c1f6.webp

???


b9271ad71f10927001b7e26d4783bbd9.webp

原文链接

828291b578f55d652668a4614b87c1f6.webp

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c136-use-multiple-inheritance-to-represent-the-union-of-implementation-attributes




觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

浏览 41
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报