1

I'm initializing an std::array at compile time with an initializer list, and I would like to have a way to store the number of elements. std::array::size() would return the size of the whole array and it's not what I'm looking for.

How could I improve the below code? Many thanks!

#include <array>

constexpr std::array<int, 5> a{{1, 2, 3}};

constexpr size_t element_count(const std::array<int, 5> &a) { return ???; }

int main() { static_assert(element_count(a) == 3); }

I'm compiling with g++ (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0.

Mihai Galos
  • 1,707
  • 1
  • 19
  • 38

2 Answers2

2

There is no way to do this nicely in C++14. The type of the array is fixed in it's declaration, and it remains the same regardless of number of elements actually initialized to non-zero values.

In C++17 you would just do

std::array arr{1, 2, 3, 4};

But in C++14 you'd have to use auto variable and make_array type of function. If you want, I can show example code.

P.S. As a matter of fact, lack of automatic array length deduction with std::array was the sole reason I was using C-style arrays in some of my code.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
0

I have found a possible workaround by using a pointer to an initializer list begin and asking for its size at compile time: constexpr array and std::initializer_list. This code compiles on the above mentioned compiler and I can use the size() and operator[] during runtime to get information from the array.

Mihai Galos
  • 1,707
  • 1
  • 19
  • 38