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

2020-04-23 15:33:56 浏览数 (4)

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

1 人点赞