前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则​T.143:避免无意中编写非通用代码

C++核心准则​T.143:避免无意中编写非通用代码

作者头像
面向对象思考
发布2020-10-10 09:56:09
2770
发布2020-10-10 09:56:09
举报

T.143: Don't write unintentionally non-generic code

T.143:避免无意中编写非通用代码

Reason(原因)

Generality. Reusability. Don't gratuitously commit to details; use the most general facilities available.

通用性。重用性。不要无故陷入细节。使用可用的,更加通用的功能。

Example(示例)

Use != instead of < to compare iterators; != works for more objects because it doesn't rely on ordering.

使用!=而不是<比较迭代器;由于不依赖有序性,!=适用于更多对象。

代码语言:javascript
复制
for (auto i = first; i < last; ++i) {   // less generic
    // ...
}

for (auto i = first; i != last; ++i) {   // good; more generic
    // ...
}

Of course, range-for is better still where it does what you want.

当然,如果确实是你想要的,范围for语句可能是更好的选择。

Example(示例)

Use the least-derived class that has the functionality you need.

使用包含你需要功能的最少继承类。

代码语言:javascript
复制
class Base {
public:
    Bar f();
    Bar g();
};

class Derived1 : public Base {
public:
    Bar h();
};

class Derived2 : public Base {
public:
    Bar j();
};

// bad, unless there is a specific reason for limiting to Derived1 objects only
void my_func(Derived1& param)
{
    use(param.f());
    use(param.g());
}

// good, uses only Base interface so only commit to that
void my_func(Base& param)
{
    use(param.f());
    use(param.g());
}
Enforcement(实施建议)
  • Flag comparison of iterators using < instead of !=. 标记使用<而不是!=进行迭代器比较的情况。
  • Flag x.size() == 0 when x.empty() or x.is_empty() is available. Emptiness works for more containers than size(), because some containers don't know their size or are conceptually of unbounded size. 如果x.empty()或者x.is_empty()可用,标记使用x.size()==0的代码。由于有些容器不知道自己的大小或者概念上是无限大的,相比size(),空判断可以用于更多的容器。
  • Flag functions that take a pointer or reference to a more-derived type but only use functions declared in a base type. 标记函数获取派生类的指针或引用却只使用到基类函数的情况。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t143-dont-write-unintentionally-non-generic-code

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-09-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
    • Enforcement(实施建议)
    相关产品与服务
    容器服务
    腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档