I'm not talking about std::array
or anything, just classic vanilla C/C++ arrays. I'm aware of the various ways ARRAY_SIZE
/ _countof
could be implemented, I'm just wondering if they've managed to standardize a name for this yet (under std::
I assume). If not is there a proposal for it?
std::extent - the size of arrays
If you are working with native arrays you can use std::extent
from <type_traits>
, which is used to yield the number of elements in the Nth dimension of an array (defaulting to the first).
int a1[1024];
int a2[std::extent<decltype(a1)>::value]; // int[1024]
A little bit of indirection (generic solution, not just arrays)
There isn't a single name that can act as a replacement for what you are describing, but since C++11 one can use std::begin
and std::end
to get iterators for a suitable entity, and together with std::distance
you have a "superb" way of getting the size of something which has the suitable qualities.
int a1[1024];
auto n = std::distance (std::begin (a1), std::end (a1)); // 1024
The drawback with the above solution is that none of the three functions are constexpr in C++11, and even in C++14 std::distance
is still not constexpr (the other two are).
This means that the solution cannot be used in contexts which require a constant-expression.
If you are sure you are working with an entity that provides RandomAccessIterators, one workaround for the workaround would be to use std::end (e) - std::begin(e)
if a constant-expression is required (C++14).
N4280 proposes that we add std::size
to the standard library, effectively being exactly what you are looking for.
int a1[1024];
auto n = std::size (a1);
If all goes as planned we will have it in C++17.
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