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

网友投稿 948 2022-10-13

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

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

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:

考虑以下代码

auto p = v.begin(); // vector::iteratorauto h = t.future();auto q = make_unique(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(示例)

templateauto Container::first() -> Iterator; // Container::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(示例)

auto lst = { 1, 2, 3 }; // lst is an initializer listauto 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可以之后,我们可以(也应该)更加明确我们推断的类型。

// ...ForwardIterator p = algo(x, y, z);

Example (C++17)

示例(C++17)

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​​

觉得本文有帮助?欢迎点赞并分享给更多的人。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:【zookeeper】——消息广播,崩溃恢复
下一篇:程序员英语进阶
相关文章

 发表评论

暂时没有评论,来抢沙发吧~