Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of built-in multidimensional array using variadic template function

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.

like image 912
Ricky65 Avatar asked Dec 27 '22 10:12

Ricky65


1 Answers

#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;
}
like image 124
kennytm Avatar answered Dec 30 '22 00:12

kennytm