温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++怎么避免无意中编写非通用代码

发布时间:2021-11-24 10:43:39 来源:亿速云 阅读:133 作者:iii 栏目:大数据

本篇内容介绍了“C++怎么避免无意中编写非通用代码”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

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.

    标记函数获取派生类的指针或引用却只使用到基类函数的情况。

“C++怎么避免无意中编写非通用代码”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI