How to get the number of elements in std::array<T, N> without having to create its instance?
Asked Answered
G

1

10

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.

Gonta answered 13/3, 2020 at 18:31 Comment(8)
If you have N, why do you need to ask array to reproduce it for you?Alfieri
@Alfieri Because sizeof(std::array<T, N>) == N * sizeof(T) doesn't have to be true.Likewise
Because the array may be typedefed elsewhere or be passed as an argument to a template.Gonta
@NathanOliver: The question is about number of elements, not size in bytes; sizeof isn't really relevant. Apparently there is a simple solution though, std::tuple_size is new to me.Alfieri
Yes I'm confused by the disparity between the title and the last sentence of the question. Do you want to know the number of elements or the number of bytes?Fractostratus
The number of elements. Using sizeof divided by an element size is a standard C trick to get that value.Gonta
If you want to know the number of elements, just use N.Fractostratus
@Gonta What is the point of all this, though? If you already have N to begin with, there is no need to go through all this to get N indirectly, or to validate that N==N. What is the actual use case that you are trying to solve?Saguache
R
14

There's std::tuple_size<std::array>.

static_assert(std::tuple_size<std::array<int, 5>>::value == 5);
Radioman answered 13/3, 2020 at 18:34 Comment(4)
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.