T.143: Don't write unintentionally non-generic code
T.143:避免无意中编写非通用代码
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());
}
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t143-dont-write-unintentionally-non-generic-code