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

Avi*_*ash 3 c++ c++11

如何auto实施C++11?我试过跟随,它的工作原理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);
Run Code Online (Sandbox Code Playgroud)

我想检查一下如何使用plain来实现 C++

Jer*_*fin 10

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

auto x = 1;
Run Code Online (Sandbox Code Playgroud)

做的有点像:

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

function(1);
Run Code Online (Sandbox Code Playgroud)

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

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

  • 不完全的.`decltype(function_that_returns_reference())`是一些`U&`,但``function(function_that_returns_reference())`会推导出`U`,就像`auto x = function_that_returns_reference()`.它是`auto`,它给我们模板中的`T`. (2认同)

Naw*_*waz 7

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

auto v = (4+5*2);
Run Code Online (Sandbox Code Playgroud)

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

int v = (4+5*2); //or simply : int v = 14;
Run Code Online (Sandbox Code Playgroud)

同样的,

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

auto e = new int[5]; //becomes int* e = new int[5];
Run Code Online (Sandbox Code Playgroud)

等等

  • @juanchopanza在这种情况下`v [i]`的类型是一些`T&`(或`T const&`).`auto x = v [i]`然而,推断出`T`,而不是'T&`.请参见此处:http://stackoverflow.com/a/8797915/46642 (2认同)