Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we have auto array in c++17?

Tags:

c++

c++17

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?

like image 706
Nandha Avatar asked Jun 13 '18 15:06

Nandha


People also ask

Can we use Auto in array?

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].

What is an auto array?

Other arrays can depend on dummy arguments, these are called automatic arrays and their size is determined by the values of dummy arguments.

Is std :: array initialized?

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};

How is array initialized in C language?

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.


3 Answers

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
like image 71
SergeyA Avatar answered Nov 11 '22 15:11

SergeyA


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.

like image 32
Barry Avatar answered Nov 11 '22 16:11

Barry


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};
like image 1
ThomasMcLeod Avatar answered Nov 11 '22 17:11

ThomasMcLeod