繁体   English   中英

如何在C ++ 11中自动实现

[英]how is auto implemented in C++11

如何在C++11 auto实现? 我试过以下,它适用于C++11

auto a = 1;
// auto = double
auto b = 3.14159;
// auto = vector<wstring>::iterator
vector<wstring> myStrings;
auto c = myStrings.begin();
// auto = vector<vector<char> >::iterator
vector<vector<char> > myCharacterGrid;
auto d = myCharacterGrid.begin();
// auto = (int *)
auto e = new int[5];
// auto = double
auto f = floor(b);

我想检查一下如何使用普通的C++实现这一点

它与函数模板中的类型推导使用的大致相同,例如:

auto x = 1;

做的有点像:

template <class T>
T function(T x) { return input; }

function(1);

编译器必须确定您作为参数传递的表达式的类型,并从中实例化具有适当类型的函数模板。 如果我们从这开始,那么decltype基本上给了我们这个模板中的T ,而auto给了我们这个模板中的x

我怀疑模板类型推导的相似性使委员会更容易接受autodecltype到语言 - 他们基本上只是添加新的方式来访问功能模板已经需要的类型推导。

在C ++中,每个表达式都有类型 例如, (4+5*2)是一个值等于14且type为int的表达式。 所以当你写这个:

auto v = (4+5*2);

编译器检测右侧表达式的类型 ,并用检测到的类型替换auto (有一些例外,读取注释) ,它变为:

int v = (4+5*2); //or simply : int v = 14;

同样的,

auto b = 3.14159; //becomes double b = 3.14159;

auto e = new int[5]; //becomes int* e = new int[5];

等等

auto关键字只是一种声明变量的方法,同时根据值输入类型。

所以你的

auto b = 3.14159;

会知道b是双倍的。

有关auto其他阅读,请查看以下参考资料

C ++ Little Wonders:C ++ 11 auto关键字redux

C ++ 0x auto关键字

它像以前一样工作:)

您是否从未遇到编译器错误告诉您:

错误:const char*int无效转换

对于这样的代码片段: int i = "4";

好吧, auto只是利用编译器知道=符号右侧表达式类型的事实,并重用它来键入你声明的变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM