摘自:
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
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;
}