C++中怎么使用auto避免多余的类型名重复

发布时间:2021-08-02 15:44:44 作者:Leah
来源:亿速云 阅读:232

今天就跟大家聊聊有关C++中怎么使用auto避免多余的类型名重复,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

Reason(原因)

Example(示例)

Consider:

考虑以下代码:

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(示例)

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(示例)

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可以之后,我们可以(也应该)更加明确我们推断的类型。

// ...
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.

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

看完上述内容,你们对C++中怎么使用auto避免多余的类型名重复有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. react避免重复点击的方法
  2. Shell脚本中怎么避免重复执行

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

c++ auto

上一篇:怎么用CSS实现图片列表悬停放大效果

下一篇:怎么用CSS实现类似条状统计表效果

相关阅读

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

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