Consider the following code:
auto numbers = {1, 2, 3, 4}; // 'numbers' is an std::intializer_list<int>
auto num_array[] = {1, 2, 3, 4} // error -> declared as an array of 'auto'
Why is this limitation in place?
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].
Other arrays can depend on dummy arguments, these are called automatic arrays and their size is determined by the values of dummy arguments.
Initialization of std::array Like arrays, we initialize an std::array by simply assigning it values at the time of declaration. For example, we will initialize an integer type std::array named 'n' of length 5 as shown below; std::array<int, 5> n = {1, 2, 3, 4, 5};
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
With C++17 and class template argument deduction, this works just fine:
#include <array>
std::array arr{1, 2, 3, 4};
int i = arr.size(); // 4
Asking why on language features is a notoriously difficult question to answer.
But the hopefully helpful version is: auto
is a very simple language feature that just does full deduction, not constrained deduction. You can add some declarators, like auto&
or auto*
, but not all of them. As-is, it's incredibly useful. Just... not all powerful. It's often useful to start with a simple, restricted feature set and then expand later as we gain experience.
With Concepts, it is possible that further power may be added to declarations to do more kinds of things, like:
std::vector<int> foo();
std::vector<auto> v = foo();
Having an array of auto
seems to fit into that mold. Definitely not in C++17, but possibly for C++20.
It's ugly, but it is possible to deduce the element type from an raw array list initializer and declare the array directly, as follows:
template<typename T>
struct array_trait
{
using element_type = T;
array_trait(T(&&)[]);
};
decltype(array_trait({4,5,7}))::element_type a[] = {4,5,7};
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