When you work with arrays, you may need to get the total number of elements the array has including sub-arrays. This can be done with some template meta-programming, by using std::extent
and std::rank
along with std::remove_extent
.
template <class T, std::size_t N = std::extent<T>::value >
struct total_elements
{
using M_type = typename std::remove_extent<T>::type;
static constexpr std::size_t value = N * total_elements< M_type >::value;
};
template <class T>
struct total_elements<T, 0> : std::integral_constant<std::size_t, 1> {};
Live example.
This can be particularly useful if you work with vector
of vectors
because the storage is not guaranteed to be contiguous: by giving the total number of elements and a 1D vector
, you will obtain that. You'll also need some pointer arithmetic to make it behave as if it were multidimensional, but that's easy to abstract in a class.
As a note, the standard does not obligate you to use it: if you find a place where it may be useful, then go for it.