Charles Ye
Charles Ye

Reputation: 51

Deduce array dimension from array name through C++ template metaprogramming

I remember that ten years ago, there was a piece of code using c++ template meta programming which can deduce the array dimensions from an array name.

For example

int a[2][3][4][5][6];
cout << DimOfArray(a) << endl

Output:

5

But I forget the details of that code. I remember it uses sizeof(a)/sizeof(a[0]) tricks. Does anyone know how to write it?

Upvotes: 5

Views: 194

Answers (2)

Geezer
Geezer

Reputation: 5710

Since C++11 you have std::rank, so this little wrapper will do what you want:

#include <type_traits>

template <typename T>
size_t DimOfArray(T const& array) constexpr
{
    return std::rank<T>::value;
}

Upvotes: 1

Aconcagua
Aconcagua

Reputation: 25526

The original code might have built what today is provided by std::rank, see section "Possible implementation"; for not having to inherit from integral constant (that wouldn't have existed in those days), it could be modified to:

template<typename T>
struct rank { static size_t const value = 0U; };

template<typename T>
struct rank<T[]> { static size_t const value = rank<T>::value + 1; };

template<class T, std::size_t N>
struct rank<T[N]> { static size_t const value = rank<T>::value + 1; };

The code then would have used this template class in the template function (the template class might have been local classes in the function as well):

template <typename T>
size_t dimOfArray(T const& array)
{
    return /*std::*/rank<T>::value;
}

With modern C++ best declare this function constexpr. If you are rather after getting the size of one specific dimension, you could use this:

template <typename T, size_t N>
size_t dimOfArray(T const (&array)[N]) constexpr
{
    return N;
}

Again, today you might want to have it constexpr (as shown).

The latter (size of a specific dimension) is what you could achieve with sizeof(a)/sizeof(*a) "tricks" as well (instead of the much simpler returning of N), I don't see, though, how you'd want to get the number of dimensions with.

Upvotes: 6

Related Questions