I want to use auto
more in my code and came up with the following example:
#include <vector>
int main() {
auto v{std::vector{}};
for (auto i{0}; i < 10; i++) {
v.push_back(i);
}
}
In this case, with GCC we get an error saying:
<source>: In function 'int main()':
<source>:4:24: error: class template argument deduction failed:
4 | auto v{std::vector{}};
Why can't the compiler see that v
must have the type std::vector<T>
where i
has the type T
? Of course, the following code will compile:
#include <vector>
int main() {
auto v{std::vector<int>{}};
for (auto i{0}; i < 10; i++) {
v.push_back(i);
}
}
As @PeteBecker commented, the type of v
has to be known when v
is defined.
auto
is simply a Placeholder type specifiers for the compiler to deduce the type at that point (based on the initialization in this case):
The type of a variable declared using a placeholder type is deduced from its initializer.
(emphasis is mine)
The fact that several lines later you add some element to the vector
does not change that.
This is not something unique to a class template like std::vector
, the same principle applies to any object.
E.g. the following will compile:
auto n = 5; // type of `n` will be deduced to `int` based on the type of `5`
But this will not:
auto n;
n = 5;
MSVC, for example, issues this error:
error C3531: 'n': a symbol whose type contains 'auto' must have an initializer