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++
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With