前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.11:使用auto避免多余的类型名重复

C++核心准则ES.11:使用auto避免多余的类型名重复

作者头像
面向对象思考
发布2020-04-23 15:33:56
9297
发布2020-04-23 15:33:56
举报
文章被收录于专栏:C++核心准则原文翻译

ES.11: Use auto to avoid redundant repetition of type names

ES.11:使用auto避免多余的类型名重复

Reason(原因)

  • Simple repetition is tedious and error-prone. 简单的重复多余且易错。
  • When you use auto, the name of the declared entity is in a fixed position in the declaration, increasing readability. 当你使用auto的时候,被定义实体的名称会出现在固定的位置,这样可以增加可读性。
  • In a template function declaration the return type can be a member type. 在模板函数定义中,返回值可以是成员类型。
Example(示例)

Consider:

考虑以下代码:

代码语言:javascript
复制
auto p = v.begin();   // vector<int>::iterator
auto h = t.future();
auto q = make_unique<int[]>(s);
auto f = [](int x){ return x + 10; };

In each case, we save writing a longish, hard-to-remember type that the compiler already knows but a programmer could get wrong.

无论哪种情况,我们都不必编写又长、类型又难记的类型信息。其实这些信息编译器已经知道,但程序员还是会弄错。

Example(示例)

代码语言:javascript
复制
template<class T>
auto Container<T>::first() -> Iterator;   // Container<T>::Iterator
Exception(例外)

Avoid auto for initializer lists and in cases where you know exactly which type you want and where an initializer might require conversion.

对于你确切地知道所需类型但初始化器可能需要转换的情况,应避免为初始化列表使用auto。

Example(示例)

代码语言:javascript
复制
auto lst = { 1, 2, 3 };   // lst is an initializer list
auto x{1};   // x is an int (in C++17; initializer_list in C++11)
Note(注意)

When concepts become available, we can (and should) be more specific about the type we are deducing:

在concepts可以之后,我们可以(也应该)更加明确我们推断的类型。

代码语言:javascript
复制
// ...
ForwardIterator p = algo(x, y, z);
Example (C++17)

示例(C++17)

代码语言:javascript
复制
auto [ quotient, remainder ] = div(123456, 73);   // break out the members of the div_t result
Enforcement(实施建议)

Flag redundant repetition of type names in a declaration.

标记在声明时发生的多余的类型名称重复。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es11-use-auto-to-avoid-redundant-repetition-of-type-names

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ES.11: Use auto to avoid redundant repetition of type names
  • Reason(原因)
    • Example(示例)
      • Exception(例外)
        • Note(注意)
          • Example (C++17)
            • Enforcement(实施建议)
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档