4

How is auto implemented in C++11? I tried following and it works in 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);

I want to check how this can be achieved using plain C++

4

4 回答 4

11

It does roughly the same thing as it would use for type deduction in a function template, so for example:

auto x = 1;

does kind of the same sort of thing as:

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

function(1);

The compiler has to figure out the type of the expression you pass as the parameter, and from it instantiate the function template with the appropriate type. If we start from this, then decltype is basically giving us what would be T in this template, and auto is giving us what would be x in this template.

I suspect the similarity to template type deduction made it much easier for the committee to accept auto and decltype into the language -- they basically just add new ways of accessing the type deduction that's already needed for function templates.

于 2012-04-18T08:12:49.070 回答
7

In C++, every expression has value and type. For example, (4+5*2) is an expression which has value equal to 14 and type is int. So when you write this:

auto v = (4+5*2);

the compiler detects the type of the expression on the right side, and replaces auto with the detected type (with some exception, read comments), and it becomes:

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

Similarly,

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

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

and so on

于 2012-04-18T07:58:10.563 回答
1

The auto keyword is simply a way to declare a variable while having it type being based upon the value.

So your

auto b = 3.14159;

Will know that b is a double.

For additional reading on auto take a look at the following references

C++ Little Wonders: The C++11 auto keyword redux

The C++0x auto keyword

于 2012-04-18T07:59:34.840 回答
1

It works like before :)

Have you never hit a compiler error telling you:

error: invalid conversion from const char* to int

for such a code fragment: int i = "4";

Well, auto simply leverages the fact that the compiler knows the type of the expression on the right hand side of the = sign and reuses it to type the variable you declare.

于 2012-04-18T09:07:47.407 回答