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

时间:2022-07-26
本文章向大家介绍C++核心准则​T.143:避免无意中编写非通用代码,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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