Saturday, April 16, 2011

How to calculate the number of dimensions of an array

Using the same idea of the two previous posts, we can calculate the number of dimensions of an array as follows:

#include <iostream>

template < typename T >
struct calc_dim
{
    static const unsigned int value = 0;
};

template < typename T, unsigned int N >
struct calc_dim< T[N] >
{
    static const unsigned int value = calc_dim< T >::value + 1;
};

int main()
{
    std::cout << calc_dim < int[5][10] >::value  << std::endl;
    std::cout << calc_dim < int[5][10][12] >::value << std::endl;
    std::cout << calc_dim < int[10] >::value << std::endl;
    std::cout << calc_dim < float[10] >::value << std::endl;
    std::cout << calc_dim < float >::value << std::endl;
}

Result:

2
3
1
1
0

No comments:

Post a Comment