开发者

How to get size of an array using metaprogramming? [duplicate]

This question already has an answer here: Closed 11 years ago.

Possible Duplicate:

Use templates to get an array's size and end address

Can someone explain this temp开发者_Go百科late code that gives me the size of an array? (the first answer includes obtaining the value as a compile time constant)

How to get size of an array using metaprogramming? Multidimensional would be also appreciated. So for example if I pass a type to this struct (how ever it's called, let's say get_dim) I would get:

get_dim<int>::value; //0
get_dim<int[1]>::value //1
get_dim<int[2][3]>::value //2,3


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:

9
5

Full Demo at Ideone : http://ideone.com/tpWk8


EDIT:

Another way (after seeing your edit),

template<typename T>
struct get_dim;

template<typename T, size_t N>
struct get_dim<T[N]>
{
    static const int value = N;
};

int main() 
{
       cout << get_dim<int[100]>::value;
       return 0;
}

Output:

100

http://ideone.com/wdFuz


EDIT:

For two dimensional arrays:

struct size2D
{
   size_t X;
   size_t Y;
};

template<typename T, size_t M, size_t N>
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:

2, 5

Code : http://ideone.com/2lrUq


This functionality is present in Boost.TypeTraits, specifically, boost::rank<> and boost::extent<>.

If you want to know how it's done, see other answers, or the Boost source code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜