Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5189
  • 博文数量: 12
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 11
  • 用 户 组: 普通用户
  • 注册时间: 2013-03-26 20:25
文章分类
文章存档

2013年(12)

我的朋友

分类: C/C++

2013-03-27 11:23:16

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


typedef unsigned char byte_t;

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

template
byte_t (&dimen(T (&a)[N]) )[N];
#define dimmensionof_v2(x) sizeof(dimen(x))

更简单的实现

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

template
int arr_size(T (&arr)[N]){

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

*/

     return SIZE ::cnt;
}

阅读(139) | 评论(0) | 转发(0) |
0

上一篇:窃取私有成员

下一篇:C++成员初始化列表

给主人留下些什么吧!~~