求传入函数中的数组长度

来源:互联网 发布:深圳房价 知乎 编辑:程序博客网 时间:2024/05/22 05:10

摘自:http://blog.chinaunix.net/u2/75321/showart_1161698.html
 
一般来说数组传入函数里面后会退化为指针,sizeof则没有用了,所以一般都要多传入一个数组长度。但是还是有办法求长度的。
下面三个方法的原理都是利用array-size函数把数组的长度骗取出来,而且利用&号过滤
指针.
template <int N>
struct size{
     static const int cnt = N;
}; 
template <typename T, int N>
size <N> array_size(T (&a)[N]);
#define dimensionof(x) array_size(x).cnt

typedef unsigned char byte_t;

template <int N>
struct size_v1{
   
     byte_t c[N];
}; 
template <typename T, int N>
size <N> array_size_v1(T (&a)[N]);
#define dimensionof_v1(x) sizeof(array_size(x).c)

template <typename T, int N>
byte_t (&dimen(T (&a)[N]) )[N];
#define dimmensionof_v2(x) sizeof(dimen(x))


更简单的实现

template <int N>
struct SIZE{
     static const int cnt = N;
};

template <typename T, int N>
int arr_size(T (&arr)[N]){

/*
     cout << sizeof(arr) / sizeof(T) << endl;//work well
     struct SIZE <N> s;//also work well
     cout << s.cnt << endl;

*/

     return SIZE <N> ::cnt;
}

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/SearchLife/archive/2008/12/19/3560200.aspx