Sunday 10 April 2011

Calculating size of arrays - one dimensional and multiple dimensional

Someone asked at stackoverflow : How to get size of an array using metaprogramming?

My solution:

For one dimensional arrays,

template<typename T, size_t N>
size_t size_of_array(T (&)[N])
{
   return N;
}
int arr[]={1,2,2,3,4,4,4,54,5};
cout << size_of_array(arr) >> endl;     

A a[] = {A(),A(), A(), A(), A()};
cout << size_of_array(a) >> endl;


Output at ideone.

For two dimensional arrays,

struct size2D
{
   size_t X;
   size_t Y;
};

template<typename T, size_t M, size_t N&lgt;
size2D size_of_array(T (&)[M][N])
{
   size2D s = { M, N};
   return s;
}
int arr[][5]={ {1,2,2,5,3}, {4,4,4,54,5}} ;
size2D size = size_of_array(arr);
cout << size.X <<", "<< size.Y << endl; 


Output at ideone.


1 comment:

  1. That is nice, Prasoon. :-)

    But then I think, you meant :

    template < typename T, std::size_t Size >
    typename type_of_size<Size>::type& sizeof_array_helper(T(&)[Size]);

    I believe, browser interpreted <Size> as HTML tag, hence its not showing it. Haha..

    ReplyDelete