In C++0x (ohh! read C++11), we have automatic type inference. One thing which made me curious was that I can't create an array of auto variables. For example:
auto A[] = {1, 2, 3, 4}; // Error!
Any ideas why this might have been disallowed?
The possibly constrained (since C++20) auto specifier can be used as array element type in the declaration of a pointer or reference to array, which deduces the element type from the initializer or the function argument (since C++14), e.g. auto (*p)[42] = &a; is valid if a is an lvalue of type int[42].
If you want to create an array whose size is a variable, use malloc or make the size a constant. Show activity on this post. The compiler needs to know the size of the array while declaring it. Because the size of an array doesn't change after its declaration.
The C99 standard allows variable sized arrays (see this). But, unlike the normal arrays, variable sized arrays cannot be initialized.
Automatic arrays, unlike automatic variables, cannot be initialized.
auto
deduces every brace-enclosed initializer list to a std::initializer_list<T>
. (See §7.1.6.4.6 including the example).
Unfortunately you cannot initialize an array or even std::array
from a std::initializer_list
once you have obtained it, but you can use a std::vector
.
#include <vector>
#include <array>
#include <initializer_list>
int main()
{
auto x = {1,2,3};
std::array<int, 3> foo1 = x; // won't work for whatever reason
std::vector<int> foo2 = x; // works as expected
return 0;
}
Of course this defeats the whole purpose of what you are trying to do.
I tried writing a work around called make_array
but had to realize that this cannot ever work as the size of an initializer_list
isn't part of its template arguments and so you only instantiate one make_array
template for each T
. This sucks.
template<typename T>
auto make_array(const std::initializer_list<T>& x)
-> std::array<T, x.size()> { } // maaah
Well, apparently you can go for the variadic-template hack mentioned here How do I initialize a member array with an initializer_list?
Because {1, 2, 3, 4}
is purely a syntactic construct- it is not an expression and does not have a type. Therefore, auto
cannot deduce its type from it.
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