C ++ auto关键字。为什么它是魔术? [英] C++ auto keyword. Why is it magic?

查看:352
本文介绍了C ++ auto关键字。为什么它是魔术?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我用来学习C ++的所有材料, auto 始终是一个奇怪的存储持续时间说明符,没有任何目的。但就在最近,我遇到的代码使用它作为一个类型名称本身。出于好奇,我尝试了,它假设了我分配给它的任何类型。

From all the material I used to learn C++, auto has always been a weird storage duration specifier that didn't serve any purpose. But just recently, I encountered code that used it as a type name in and of itself. Out of curiosity I tried it, and it assumes the type of whatever I happen to assign to it!

突然STL迭代器,以及,使用模板的任何东西10折更容易写。感觉就像我使用一种有趣的语言,如Python。

Suddenly STL iterators and, well, anything at all that uses templates is 10 fold easier to write. It feels like I'm using a 'fun' language like Python.

这个关键字在哪里是我的一生?

Where has this keyword been my whole life? Will you dash my dreams by saying it's exclusive to visual studio or not portable?

推荐答案

auto

auto was a keyword that C++ "inherited" from C that had been there nearly forever, but virtually never used because there were only two possible conditions: either it wasn't allowed, or else it was assumed by default.

使用 auto 来表示推导出的类型是C ++ 11的新特性(以前称为C ++ 0x )。由于C ++ 11标准最近发布了,可能仍有一些编译器尚未更新以便了解它。

The use of auto to mean a deduced type is new with C++11 (formerly called C++0x). Since the C++11 standard was published extremely recently, there may still be some compilers that haven't been updated to understand it (yet).

同时, auto x 的工作原理与函数模板的模板类型推导工作大致相同。考虑这样的功能模板:

At the same time, auto x works pretty much the same way as template type deduction works for function templates. Consider a function template like this:

template<class T>
int whatever(T t) { 
    // point A
};

在A点,一个类型已分配给 T 基于传递给参数的值,无论。当你执行 auto x = some_expression; 时,基本上使用相同的类型推导机制来确定 x 的类型 some_expression 的类型,用于初始化它。

At point A, a type has been assigned to T based on the value passed for the parameter to whatever. When you do auto x = some_expression;, essentially the same type deduction mechanism is used to determine the type for x from the type of some_expression that's used to initialize it.

这意味着大多数类型的减法机制实现 auto 已经存在,并用于任何编译器的模板,甚至尝试实现C ++ 98/03。因此,即使对于那些不支持C ++ 11的编译器,添加对 auto 的支持也许会是相当快速和容易的。

This means that most of the type deduction mechanics a compiler needs to implement auto are already present and used for templates on any compiler that even sort of attempts to implement C++98/03. As such, even for those compilers that don't support C++11 yet, adding support for auto will probably be fairly quick and easy.

因此, auto 现在可能不是完全可移植的,关闭,我希望它相当快地添加到休息。

As such, auto may not be completely portable right now, but it's pretty close and I'd expect it to be added to the rest relatively quickly.

这篇关于C ++ auto关键字。为什么它是魔术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆