In C++11 it is possible to create a function which returns the size (number of elements) of a built-in one dimensional array at compile time using constexpr. Example below:
template <typename T, std::size_t N>
constexpr std::size_t size(T (&array)[N])
{
return N;
}
This is a superior alternative to ARRAY_SIZE and similar macros imo.
However, this will only return the size of the most significant dimension of a built-in multidimensional array.
I use the following function for determining the size of a built-in two dimensional array:
template <typename T, std::size_t N, std::size_t N2>
constexpr std::size_t size(T (&array)[N][N2])
{
return N * N2;
}
Ideally, it would be very useful to have a function that returns the size of a built-in array with an arbitrary number of dimensions. I thought variadic templates may help but I couldn't see a way of unpacking the template paramters as only one argument is passed. Is such a function possible?
Thanks in advance.
#include <type_traits>
#include <cstdlib>
template <typename T>
constexpr size_t size(const T&) noexcept
{
return sizeof(T)/sizeof(typename std::remove_all_extents<T>::type);
}
Example:
#include <cstdio>
int main()
{
int a[3][4][7][12];
char f[6];
printf("%lu == %ld ?\n", size(a), 3*4*7*12);
printf("%lu == %ld ?\n", size(f), 6);
return 0;
}
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