There is std::array<T, N>::size()
, but it's non-static, so it requires an instance of std::array
. Is there a way to get the value it returns (which is the N
of std::array<T, N>
) without having to construct an instance of the array? For a normal array, I could have used sizeof
, but I see no guarantee that sizeof(std::array<T, N>) == N * sizeof(T)
be true.
How to get the number of elements in std::array<T, N> without having to create its instance?
There's std::tuple_size<std::array>
.
static_assert(std::tuple_size<std::array<int, 5>>::value == 5);
Wouldn't plain std::size() do? –
Selfgovernment
@JesperJuhl Actually no,
std::size()
requires an instance of the array. –
Radioman It doesn't make sense to use
tuple_size
like this though, if you already know the array size up front to pass it into the template. Maybe this would be a more meaningful example? using ArrayType = std::array<int, 5>; ... static_assert(std::tuple_size<ArrayType>::value == 5);
–
Saguache @RemyLebeau I guess the O/P is thinking the array decl has been passed in as a template argument to a template function? Even then the only purpose I can see is to assign it as the returned object, which still requires an instance to be created. –
Trollop
© 2022 - 2024 — McMap. All rights reserved.
N
, why do you need to askarray
to reproduce it for you? – Alfierisizeof(std::array<T, N>) == N * sizeof(T)
doesn't have to be true. – Likewisesizeof
isn't really relevant. Apparently there is a simple solution though,std::tuple_size
is new to me. – Alfierisizeof
divided by an element size is a standard C trick to get that value. – GontaN
. – FractostratusN
to begin with, there is no need to go through all this to getN
indirectly, or to validate thatN==N
. What is the actual use case that you are trying to solve? – Saguache