Reputation: 13257
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++
Upvotes: 4
Views: 2120
Reputation: 361342
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
Upvotes: 7
Reputation: 299770
It works like before :)
Have you never hit a compiler error telling you:
error: invalid conversion from
const char*
toint
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.
Upvotes: 1
Reputation: 490108
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.
Upvotes: 11
Reputation: 3276
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
Upvotes: 1