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.

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

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.

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

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:///isocpp/CppCoreGuidelines/blob/master/#t143-dont-write-unintentionally-non-generic-code​

 

新书介绍

​《实战Python设计模式》​​是作者最近出版的新书,拜托多多关注!

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

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。

 


 

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

关注微信公众号【面向对象思考】轻松学习每一天!

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

 

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